Dictionaries and Sets · Lesson 19 of 39
Dictionaries
A list finds things by position: item 0, item 1, item 2. But real data is usually looked up by name: a student's marks by roll number, a product's price by its code, a word's meaning by the word itself. That is what a dictionary (dict) is for.
In this lesson
- Keys, values and how lookup works
- Reading safely with
get() - Adding, updating, deleting and looping
- Nested dictionaries and the counting pattern
Creating a dictionary
student = {
"name": "Tanvi",
"roll": 23,
"subjects": ["Maths", "Physics"],
"hostel": False,
}
print(student["name"])
print(student["subjects"][0])
print(len(student))
Tanvi Maths 4
Each key points to a value
"name""Tanvi"str"roll"23int"subjects"["Maths", "Physics"]list"hostel"Falsebool
- Keys must be unique and immutable (strings, numbers, tuples).
- Values can be anything, including lists and other dictionaries.
- Dictionaries remember the order in which keys were added (guaranteed since Python 3.7).
How lookup works (and why it is fast)
Python runs each key through a hash function that turns it into a number, and uses that number to jump straight to the right slot. Looking up a key takes about the same time whether the dictionary has ten entries or ten million.
student["roll"]
- hash("roll")key → a number
- Find the slotnumber → position in a hidden table
- Return the value23 – no searching through other keys
This is also why keys must be immutable: if a key could change, its hash would change and Python could never find it again.
Reading safely with get()
prices = {"tea": 20, "coffee": 35}
print(prices.get("coffee"))
print(prices.get("juice")) # None instead of an error
print(prices.get("juice", 0)) # or your own default
print("tea" in prices)
print(prices["juice"])
35
None
0
True
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(prices["juice"])
KeyError: 'juice'Common mistake: KeyError on missing keys
d["key"] crashes when the key is missing. Use d.get("key", default) when absence is normal, or check with if "key" in d: first.
Adding, updating and deleting
profile = {"name": "Arjun", "city": "Jaipur"}
profile["age"] = 29 # add a new key
profile["city"] = "Udaipur" # update an existing one
profile.update({"job": "Analyst", "age": 30})
print(profile)
removed = profile.pop("job") # remove and return
del profile["age"]
print(removed, profile)
profile.setdefault("country", "India") # add only if missing
print(profile)
{'name': 'Arjun', 'city': 'Udaipur', 'age': 30, 'job': 'Analyst'}
Analyst {'name': 'Arjun', 'city': 'Udaipur'}
{'name': 'Arjun', 'city': 'Udaipur', 'country': 'India'}You can also merge dictionaries with |: defaults | user_settings returns a new dict where the right side wins.
Looping over a dictionary
stock = {"apples": 40, "pears": 0, "plums": 12}
for fruit in stock: # keys
print(fruit, end=" ")
print()
print(list(stock.values()))
for fruit, qty in stock.items(): # key and value together
if qty == 0:
print(f"Reorder {fruit}!")
apples pears plums [40, 0, 12] Reorder pears!
Common mistake: changing size while looping
Adding or deleting keys inside for k in d: raises RuntimeError: dictionary changed size during iteration. Loop over a copy instead: for k in list(d):.
Nested dictionaries
Data from APIs and JSON files is usually dictionaries inside dictionaries:
order = {
"id": 5521,
"customer": {"name": "Leela", "city": "Chennai"},
"items": [
{"sku": "BK-01", "qty": 2, "price": 299},
{"sku": "PN-07", "qty": 5, "price": 20},
],
}
print(order["customer"]["city"])
total = sum(item["qty"] * item["price"] for item in order["items"])
print("Total:", total)
Chennai Total: 698
The counting pattern
Counting how often things occur is a classic dictionary job (and a frequent interview question):
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
most = max(counts, key=counts.get)
print("Most common:", most)
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
Most common: theThe collections.Counter class does this in one line – see the lesson after next.
Grouping with a dictionary of lists
employees = [("Asha", "IT"), ("Ben", "HR"), ("Chen", "IT"), ("Dia", "Sales")]
by_dept = {}
for name, dept in employees:
by_dept.setdefault(dept, []).append(name)
print(by_dept)
{'IT': ['Asha', 'Chen'], 'HR': ['Ben'], 'Sales': ['Dia']}Practice
Try it yourself
Count how many times each character appears in "banana".
Show solution
counts = {} for ch in "banana": counts[ch] = counts.get(ch, 0) + 1 print(counts){'b': 1, 'a': 3, 'n': 2}Swap keys and values of
{"a": 1, "b": 2, "c": 3}.Show solution
d = {"a": 1, "b": 2, "c": 3} print({v: k for k, v in d.items()}){1: 'a', 2: 'b', 3: 'c'}From
{"Ravi": 72, "Sana": 91, "Tom": 85}, print the names sorted by marks, highest first.Show solution
marks = {"Ravi": 72, "Sana": 91, "Tom": 85} for name in sorted(marks, key=marks.get, reverse=True): print(name, marks[name])Sana 91 Tom 85 Ravi 72
Quick check
What does d.get("x", 5) return when "x" is missing?
5, the default.
Can a list be a dictionary key?
No – keys must be hashable (immutable). Use a tuple instead.
Which method loops over keys and values together?
.items()
Summary
- A dict maps unique, immutable keys to values; lookup by key is very fast.
- Use
get()for safe reads,update()/|to merge,pop()/delto remove. - Loop with
.items(); don't add or remove keys while looping. counts[k] = counts.get(k, 0) + 1is the classic counting pattern.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.