Introduction & Syntax
Dictionaries · Study material
A dictionary maps keys to values: a roll number to a student, a word to its count, a product code to its price. Lookups by key are fast however large the dictionary grows, and since Python 3.7 dictionaries remember the order in which keys were inserted. Dictionaries power JSON data, configuration, caches and counting – and they appear in almost every coding interview. This topic covers creating, reading, updating and looping over dicts, the counting and grouping idioms, nested dicts and sorting, then 50 practice questions run on Python 3.
On this page
- Creating dicts: literals, dict(), zip, fromkeys, comprehensions
- Reading safely: [] vs get(), in
- Adding, updating and deleting: update, del, pop, popitem, |
- keys(), values(), items() and looping
- Counting and grouping: get, setdefault, defaultdict, Counter
- Nested dicts, sorting by value and merging
Creating dictionaries
Write {key: value, …}, call dict() with keyword arguments or with key–value pairs (for example from zip), use dict.fromkeys(keys, value), or build one with a comprehension {k: v for …}. Keys must be hashable (str, int, float, tuple of hashables …) and are unique; values can be anything.
student = {"name": "Asha", "age": 20, "branch": "CSE"} # key: value pairs
prices = dict(tea=20, coffee=35) # keyword form (string keys)
pairs = dict([("a", 1), ("b", 2)]) # from pairs
zipped = dict(zip(["x", "y"], [10, 20]))
zeros = dict.fromkeys(["math", "physics"], 0)
squares = {n: n * n for n in range(1, 5)} # dict comprehension
print(student["name"], len(student))
print(prices, pairs, zipped)
print(zeros, squares)
Asha 3
{'tea': 20, 'coffee': 35} {'a': 1, 'b': 2} {'x': 10, 'y': 20}
{'math': 0, 'physics': 0} {1: 1, 2: 4, 3: 9, 4: 16}Reading values: [] versus get()
d[key] raises KeyError when the key is missing; d.get(key, default) returns the default (None if omitted) instead. key in d tests keys only – use value in d.values() to search values.
stock = {"pen": 40, "pencil": 0}
print(stock["pen"]) # [] raises KeyError for a missing key
print(stock.get("eraser")) # get() returns None instead …
print(stock.get("eraser", 0)) # … or the default you give
print("pencil" in stock, 40 in stock) # in tests KEYS, not values
try:
stock["eraser"]
except KeyError as e:
print("KeyError:", e)
40 None 0 True False KeyError: 'eraser'
Adding, updating and deleting
Assigning to a key adds it, or replaces its value if it exists – a dict never holds duplicate keys. update() (or |=) merges another mapping. del d[k] and pop(k) remove a key (pop returns the value and accepts a default), popitem() removes the most recently inserted pair, and clear() empties the dict.
marks = {"Asha": 91, "Ravi": 78}
marks["Meera"] = 85 # add a new key
marks["Ravi"] = 80 # assigning to an existing key replaces the value
marks.update({"Dev": 66, "Asha": 93})
print(marks)
del marks["Dev"] # KeyError if missing
gone = marks.pop("Meera") # remove and return the value
last = marks.popitem() # remove and return the LAST inserted pair
print(gone, last, marks)
print(marks.pop("Zoya", "not found")) # pop with a default never raises
{'Asha': 93, 'Ravi': 80, 'Meera': 85, 'Dev': 66}
85 ('Ravi', 80) {'Asha': 93}
not foundkeys(), values(), items() and looping
Looping over a dict gives its keys in insertion order. items() gives (key, value) pairs ready to unpack. The three methods return views that reflect later changes to the dict. Do not add or remove keys while looping over a dict – that raises RuntimeError; loop over list(d) instead.
cart = {"book": 450, "pen": 20, "bag": 1200}
for item in cart: # looping over a dict gives its keys
print(item, end=" ")
print()
for item, price in cart.items(): # key–value pairs
print(f"{item}: {price}")
print(list(cart.keys()), list(cart.values()), sum(cart.values()))
keys = cart.keys() # a live VIEW, not a copy
cart["ink"] = 60
print(keys)
book pen bag book: 450 pen: 20 bag: 1200 ['book', 'pen', 'bag'] [450, 20, 1200] 1670 dict_keys(['book', 'pen', 'bag', 'ink'])
Counting and grouping
Two idioms appear everywhere: counts[k] = counts.get(k, 0) + 1 to count, and groups.setdefault(k, []).append(x) to group. The collections module packages them: defaultdict(list) creates missing values automatically, and Counter counts an iterable in one call and offers most_common().
from collections import Counter, defaultdict
text = "the cat and the hat and the bat"
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1 # the classic counting idiom
print(counts)
groups = {}
for w in ["apple", "avocado", "banana", "blueberry", "cherry"]:
groups.setdefault(w[0], []).append(w) # create the list on first use
print(groups)
by_len = defaultdict(list) # missing keys get a fresh list
for w in text.split():
by_len[len(w)].append(w)
print(dict(by_len))
print(Counter(text.split()).most_common(2))
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
{3: ['the', 'cat', 'and', 'the', 'hat', 'and', 'the', 'bat']}
[('the', 3), ('and', 2)]Nested dictionaries
A value can be another dict, giving JSON-like records: company["IT"]["staff"]. Chain get() with an empty dict as the default to read deep values safely.
company = {
"IT": {"head": "Asha", "staff": 12},
"HR": {"head": "Ravi", "staff": 4},
}
company["IT"]["staff"] += 3 # reach in with two keys
company["Sales"] = {"head": "Meera", "staff": 7}
for dept, info in company.items():
print(f"{dept:<6}{info['head']:<7}{info['staff']}")
total = sum(info["staff"] for info in company.values())
print("Total staff:", total)
print(company.get("Legal", {}).get("head", "no such department"))
IT Asha 15 HR Ravi 4 Sales Meera 7 Total staff: 26 no such department
Sorting and merging
sorted(d) sorts the keys; sorted(d, key=d.get) sorts keys by their values; sorted(d.items(), key=…) sorts pairs, which dict() can turn back into an ordered dict. max(d, key=d.get) finds the key with the largest value. Merge with a | b (3.9+) or {**a, **b} – for duplicate keys, the right-hand value wins.
scores = {"Ravi": 78, "Asha": 91, "Meera": 85}
print(sorted(scores)) # keys, alphabetically
print(sorted(scores, key=scores.get, reverse=True)) # keys by value
print(dict(sorted(scores.items(), key=lambda kv: kv[1])))
print(max(scores, key=scores.get))
defaults = {"theme": "light", "font": 14}
user = {"font": 16}
print(defaults | user) # merge (3.9+): the right side wins
print({**user, **defaults}) # older spelling; here defaults win
['Asha', 'Meera', 'Ravi']
['Asha', 'Meera', 'Ravi']
{'Ravi': 78, 'Meera': 85, 'Asha': 91}
Asha
{'theme': 'light', 'font': 16}
{'font': 14, 'theme': 'light'}Common mistakes
- d[key] for a key that may be missing – KeyError; use get().
- value in d – searches keys; use
in d.values(). - dict.fromkeys(keys, []) – every key shares ONE list.
- Changing a dict's size while looping over it – RuntimeError.
- Using a list as a key – unhashable; use a tuple.
- copy() of a nested dict – inner dicts are still shared; use deepcopy().
- sum(d) – adds the keys, not the values.
Key points to remember
- Dicts map unique, hashable keys to values, in insertion order.
- [] raises KeyError; get() returns a default.
- in tests keys; iterating gives keys; items() gives pairs.
- Assigning to an existing key replaces its value.
- get(k, 0) + 1 counts; setdefault(k, []) groups.
- Counter and defaultdict simplify both.
- In a merge the right-hand value wins.
Frequently asked questions
Are dictionaries ordered?
Yes, since Python 3.7 they keep insertion order. Equality, however, ignores order: {"a": 1, "b": 2} == {"b": 2, "a": 1}.
Why are dictionary lookups fast?
A dict is a hash table: the key's hash points almost directly to its slot, giving average O(1) lookups, inserts and deletes.
dict or list of tuples?
Use a dict when you look things up by key; a list of tuples when order and duplicates matter and you mostly iterate.
Where can I learn more?
Read Python Dictionaries and Choosing the Right Collection in the Python tutorial, then practise with the exercises below.