Dictionaries in Python
Key-value pairs for fast lookups, mappings and structured data
Dictionaries store data as key-value pairs. They are the closest Python equivalent to a VLOOKUP table — you look up a value by its key in O(1) time. In data analysis, dictionaries are used for: mapping codes to labels, counting category frequencies, storing aggregated results, and passing configuration to functions.
Pandas DataFrames are built on dictionaries — a DataFrame is essentially a dictionary of column names mapped to lists of values.
Examples
Key Points
- ✓Dictionary keys must be unique and immutable (strings, numbers, tuples)
- ✓Use .get() instead of [] for safe access without KeyError
- ✓dict.items() returns key-value pairs — use it in for loops
- ✓Dictionaries maintain insertion order in Python 3.7+
- ✓In Pandas, pd.DataFrame({"col1": [...], "col2": [...]}) creates a DataFrame from a dict
Practice Question
What does analyst.get("salary", 0) return if "salary" is not a key in the analyst dictionary?