TutorialsPythonDictionaries in Python

Dictionaries in Python

Store key-value pairs — perfect for lookup tables, configs, and JSON data

A dictionary stores data as key-value pairs — like a lookup table. Each key maps to a value. Dictionaries are how you handle JSON data (from APIs), configuration settings, and column-level metadata in data work. In pandas, a DataFrame is essentially a dictionary of column names → Series. Understanding dictionaries makes pandas much easier to grasp.

Syntax

my_dict = {"key1": value1, "key2": value2}
my_dict["key1"]           # access value
my_dict["key3"] = value3  # add new key-value

Examples

Dictionary basics and data analyst use cases
# Create a dictionary
analyst = {
    "name": "Priya Sharma",
    "city": "Noida",
    "salary": 75000,
    "skills": ["SQL", "Python", "Power BI"],
    "active": True
}

# Access values
analyst["name"]          # "Priya Sharma"
analyst["skills"]        # ["SQL", "Python", "Power BI"]
analyst.get("salary")    # 75000 (safe — no KeyError if missing)
analyst.get("bonus", 0)  # 0 (default if key missing)

# Modify
analyst["salary"] = 85000  # update
analyst["experience"] = 2  # add new key

# Useful methods
analyst.keys()    # dict_keys(["name", "city", ...])
analyst.values()  # dict_values(["Priya Sharma", ...])
analyst.items()   # dict_items([("name","Priya",...)])

# Check key exists
"city" in analyst  # True

# Delete
del analyst["active"]
Dictionary for data mapping — very common in cleaning
# Map city names to zones
city_zone = {
    "Noida": "NCR",
    "Gurgaon": "NCR",
    "Delhi": "NCR",
    "Mumbai": "West",
    "Pune": "West",
    "Bengaluru": "South"
}

# Use in pandas column mapping
# df["Zone"] = df["City"].map(city_zone)

# Rename columns with a dict
rename_map = {
    "Emp_Name": "Employee Name",
    "Dept": "Department",
    "Sal": "Salary"
}
# df.rename(columns=rename_map, inplace=True)

# Replace values
gender_map = {"M": "Male", "F": "Female", "O": "Other"}
# df["Gender"] = df["Gender"].map(gender_map)
💡 dict.map() in pandas is the most common use of dictionaries in data analysis — standardise and recode column values.

Key Points

  • Use .get(key, default) instead of dict[key] — avoids KeyError on missing keys
  • Dictionaries preserve insertion order in Python 3.7+
  • Keys must be immutable (str, int, tuple) — lists cannot be keys
  • In pandas: df.rename(columns={old: new}), df["col"].map({val: new_val})
  • JSON data from APIs is loaded as Python dictionaries — learn to navigate nested dicts

Practice Question

What does my_dict.get("bonus", 0) return if "bonus" is not a key in my_dict?