Skip to main content
PYSPARK โ€ข LESSON 142

Key-Value Dictionaries with create_map()

How do we construct a dynamic MapType column containing key-value pairs for environment and tier?

Advancedโฑ 2 Minutesโญ 750 XP
๐Ÿค” THE QUESTION

How do we construct a dynamic MapType column containing key-value pairs for environment and tier?

๐Ÿ’ก WHAT IS IT?

create_map(*cols) creates a MapType column from alternating key and value expressions.

๐ŸŽฏ WHAT IS IT USED FOR?

Dynamic attribute storage, unstructured metadata tagging, and key-value feature extraction.

๐Ÿ’ป EXAMPLE
from pyspark.sql.functions import col, create_map, lit

df = df.withColumn("attributes", create_map(lit("env"), col("env"), lit("tier"), col("tier")))

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Key-Value Dictionaries with create_map().

  • โœ“ Import create_map and lit
  • โœ“ Construct key-value pairs in MapType
  • โœ“ Store dynamic attributes column