Python Dictionaries
Key-value pairs — O(1) lookup by key, Python's built-in hash map.
Creating dictionaries
Python
person = {"name": "Raman", "age": 28, "city": "Bangalore"}
empty = {}
empty2 = dict()
# From keyword arguments:
d = dict(name="Alice", age=30)
# From a list of pairs:
d = dict([(("a", 1), ("b", 2))])
Accessing values
Python
person = {"name": "Raman", "age": 28}
person["name"] # "Raman" — raises KeyError if missing
person.get("age") # 28 — returns None if missing
person.get("email", "N/A") # "N/A" — default value
Adding and updating
Python
person["email"] = "raman@example.com" # add new key
person["age"] = 29 # update existing
person.update({"age": 30, "city": "Mumbai"}) # batch update
# setdefault — set only if key doesn't exist:
person.setdefault("country", "India") # adds "India" if not present
Removing keys
Python
del person["email"] # delete; KeyError if not found
person.pop("age") # remove and return value
person.pop("x", None) # safe pop — no error if missing
person.clear() # empty dict
Looping over dictionaries
Python
d = {"a": 1, "b": 2, "c": 3}
for key in d: # loop over keys
print(key)
for key, val in d.items(): # loop over key-value pairs
print(f"{key}: {val}")
for val in d.values(): # loop over values only
print(val)
Dictionary comprehension
Python
squares = {x: x**2 for x in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}
# Flip keys and values:
d = {"a": 1, "b": 2}
flipped = {v: k for k, v in d.items()}
# {1:"a", 2:"b"}
Common patterns
Python
# Count occurrences:
words = ["apple", "banana", "apple", "cherry", "banana"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
# Or use Counter:
from collections import Counter
counts = Counter(words)
# Counter({'apple': 2, 'banana': 2, 'cherry': 1})