Dictionaries in Python
Store data as key–value pairs, look values up by key, add, update and delete entries, and loop over a dictionary.
Learning objectives
- →Create dictionaries and read values by key
- →Add, update and delete key–value pairs
- →Loop over keys, values and items
- →Use get(), update(), pop(), setdefault() and fromkeys(), and count things with a dictionary
💡 Key points
- A dictionary (dict) stores key: value pairs inside { }. You look up a value by its key, not by a position.
- Keys must be unique and immutable (str, int, tuple). Values can be anything, even lists or other dicts.
- d[key] raises KeyError if the key is missing; d.get(key, default) returns the default instead.
- d[key] = value adds the pair if the key is new, or replaces the old value if the key already exists.
- keys(), values() and items() let you loop over a dict; items() gives (key, value) tuples.
- del d[key] and d.pop(key) remove one entry; d.clear() empties the dictionary.
- Since Python 3.7, dictionaries remember the order in which keys were added.
💻 Code examples(6)
student = {"name": "Amit", "class": 12,
"marks": 87}
print(student["name"])
print(student["marks"])
print(len(student)) # number of pairs
# print(student["age"]) # KeyError: 'age'
print(student.get("age"))
print(student.get("age", "not given"))
Amit 87 3 None not given
prices = {"pen": 10, "pencil": 5}
prices["eraser"] = 3 # new key: added
prices["pen"] = 12 # existing key: updated
print(prices)
del prices["pencil"]
print(prices)
removed = prices.pop("eraser")
print(removed, prices)
prices.update({"pen": 15, "ruler": 20})
print(prices)
{'pen': 12, 'pencil': 5, 'eraser': 3}
{'pen': 12, 'eraser': 3}
3 {'pen': 12}
{'pen': 15, 'ruler': 20}marks = {"Amit": 87, "Priya": 92, "Ravi": 76}
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
for name, m in marks.items():
print(f"{name} scored {m}")
avg = sum(marks.values()) / len(marks)
print("Class average:", avg)
['Amit', 'Priya', 'Ravi']
[87, 92, 76]
[('Amit', 87), ('Priya', 92), ('Ravi', 76)]
Amit scored 87
Priya scored 92
Ravi scored 76
Class average: 85.0text = "programming"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
# the same thing, shorter, with get()
freq2 = {}
for ch in text:
freq2[ch] = freq2.get(ch, 0) + 1
print(freq2 == freq)
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
Truesubjects = ["Maths", "Physics", "CS"]
marks = dict.fromkeys(subjects, 0)
print(marks)
marks["CS"] = 95
marks.setdefault("English", 80) # missing: added
marks.setdefault("CS", 10) # exists: no change
print(marks)
backup = marks.copy()
print(marks.popitem()) # removes last added
print(sorted(backup)) # keys, A to Z
print(max(backup, key=backup.get))
{'Maths': 0, 'Physics': 0, 'CS': 0}
{'Maths': 0, 'Physics': 0, 'CS': 95, 'English': 80}
('English', 80)
['CS', 'English', 'Maths', 'Physics']
CSstudents = {
101: {"name": "Amit", "marks": 87},
102: {"name": "Priya", "marks": 92},
103: {"name": "Ravi", "marks": 76},
}
roll = 102
if roll in students:
s = students[roll]
print(f"{s['name']} scored {s['marks']}")
toppers = [s["name"] for s in students.values()
if s["marks"] >= 85]
print("85 and above:", toppers)
Priya scored 92 85 and above: ['Amit', 'Priya']
🎯 Practice
Q1. What does d.get('x', 0) return if 'x' is not a key of d?+
0, the default you passed. d['x'] would raise KeyError instead.
Q2. Can a list be used as a dictionary key?+
No. Keys must be immutable, so a list raises TypeError: unhashable type: 'list'. Use a tuple instead.
Q3. Write a program to count how many times each word appears in 'the cat and the hat'.+
count = {} for w in 'the cat and the hat'.split(): count[w] = count.get(w, 0) + 1 print(count) # {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
Q4. What is printed? d = {'a': 1, 'b': 2}; d['a'] = 5; print(len(d))+
2. Assigning to an existing key replaces its value; it does not add a new pair.
Q5. What is the difference between pop() and popitem()?+
pop(key) removes the given key and returns its value. popitem() removes and returns the last added (key, value) pair.
📝 Notes
List or dictionary?
- A list is best when items are in a sequence and you reach them by position:
marks[0]. - A dictionary is best when each value has a label and you reach it by name:
marks["Amit"].
Looking up a key is fast even when the dictionary holds thousands of entries, because Python does not search through the items one by one.
Dictionary comprehension
Like the list comprehensions you saw with loops, you can build a dict in one line:
squares = {n: n * n for n in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
passed = {k: v for k, v in marks.items() if v >= 33}
Building a dict with dict()
d1 = dict(name="Neha", age=16)
d2 = dict([("a", 1), ("b", 2)])
d3 = dict(zip(["x", "y"], [10, 20]))
All three are handy when the data comes from somewhere else, such as two lists or user input.
Common mistakes
- KeyError: reading
d["Rahul"]when there is no such key. Check withif "Rahul" in d:or useget(). - Using positions:
d[0]does not mean "first item" — it looks for the key0. - Changing size while looping: deleting keys inside
for k in d:raises RuntimeError: dictionary changed size during iteration. Loop overlist(d)instead. - Duplicate keys:
{"a": 1, "a": 2}keeps only the last value,{'a': 2}. - Thinking
inchecks values:87 in markslooks at keys. Use87 in marks.values().
Next: Day 14 — Sets, for collections of unique items.