TutorialsPythonDictionaries in Python

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

Dictionary operations
# Create
analyst = {
    "name": "Rahul Sharma",
    "city": "Noida",
    "skills": ["Python", "SQL", "Power BI"],
    "experience": 2,
}

# Access
analyst["name"]              # "Rahul Sharma"
analyst.get("salary", 0)    # 0 (safe — no KeyError if missing)

# Modify
analyst["experience"] = 3   # update
analyst["tools"] = "Excel"  # add new key

# Delete
del analyst["tools"]
analyst.pop("tools", None)  # safe delete (no error if missing)

# Iterate
for key, value in analyst.items():
    print(f"{key}: {value}")

# Check key
"city" in analyst     # True
"salary" in analyst   # False

# Common dict methods
analyst.keys()    # dict_keys(['name', 'city', ...])
analyst.values()  # dict_values(['Rahul Sharma', 'Noida', ...])
Dict comprehensions and practical patterns
# Dict comprehension — build dict from lists
regions = ["Delhi", "Noida", "Gurgaon"]
targets = [500000, 320000, 280000]

target_map = {r: t for r, t in zip(regions, targets)}
# {"Delhi": 500000, "Noida": 320000, "Gurgaon": 280000}

# Counting with dict
cities = ["Delhi", "Noida", "Delhi", "Gurgaon", "Delhi", "Noida"]
count = {}
for city in cities:
    count[city] = count.get(city, 0) + 1
# {"Delhi": 3, "Noida": 2, "Gurgaon": 1}

# Better: use collections.Counter
from collections import Counter
count = Counter(cities)  # same result, cleaner

# Map codes to labels (replaces VLOOKUP logic)
region_map = {"DL": "Delhi", "UP": "Uttar Pradesh", "HR": "Haryana"}
code = "DL"
label = region_map.get(code, "Unknown")   # "Delhi"

# In Pandas: replace codes with labels
# df["Region"] = df["RegionCode"].map(region_map)
💡 dict.get(key, default) is safer than dict[key] — it returns the default instead of raising KeyError.

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?

Related Topics

Python ListsStore, access and manipulate collections of data with Python listsFunctions in PythonWrite reusable functions to avoid repeating logic across your analysis scriptsPandas DataFramesThe core Pandas data structure — a 2D table with rows and columns