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-valueExamples
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?