A dictionary maps keys to values
A dictionary (dict) stores pairs: a key you look up, and the value it leads to. Think of a phone book: the name is the key, the number is the value.
student = {
"name": "Asha",
"class": 10,
"marks": 91,
}
print(student["name"]) # Asha
- Dictionaries use curly brackets
{}andkey: valuepairs. - Keys must be unique and unchangeable (usually strings or numbers).
- Values can be anything, including lists and other dictionaries.
- Since Python 3.7 a dictionary remembers the order items were added.
Reading values safely
print(student["city"]) # KeyError: 'city'
print(student.get("city")) # None, no error
print(student.get("city", "NA")) # NA -- a default value
print("marks" in student) # True -- 'in' checks the keys
Add, update and delete
student["city"] = "Ranchi" # new key: adds it
student["marks"] = 95 # existing key: updates it
student.update({"class": 11, "house": "Blue"})
del student["house"] # delete a key
marks = student.pop("marks") # delete and return the value
Looping through a dictionary
prices = {"tea": 10, "samosa": 15, "coffee": 20}
for item in prices: # keys
print(item)
for price in prices.values(): # values
print(price)
for item, price in prices.items(): # both together
print(f"{item:<8} Rs {price}")
| Method | Gives |
|---|---|
keys() | all the keys |
values() | all the values |
items() | (key, value) pairs |
get(k, default) | the value, or default if k is missing |
pop(k) | removes k and returns its value |
update(other) | adds or overwrites pairs from other |
Counting with a dictionary
Counting how often each thing appears is one of the most common uses of a dictionary.
votes = ["Asha", "Ravi", "Asha", "Meena", "Asha", "Ravi"]
count = {}
for name in votes:
count[name] = count.get(name, 0) + 1
print(count) # {'Asha': 3, 'Ravi': 2, 'Meena': 1}
winner = max(count, key=count.get)
print("Winner:", winner)
count.get(name, 0) gives 0 the first time a name appears, so the line works for new and old names alike.
Nested data: a list of dictionaries
A list of dictionaries works like a table: each dictionary is one row.
students = [
{"name": "Asha", "marks": 91},
{"name": "Ravi", "marks": 78},
{"name": "Meena", "marks": 85},
]
for s in students:
print(s["name"], s["marks"])
topper = max(students, key=lambda s: s["marks"])
print("Topper:", topper["name"])
Nested dictionaries
report = {
"Asha": {"maths": 95, "science": 88},
"Ravi": {"maths": 72, "science": 80},
}
print(report["Asha"]["science"]) # 88
for name, subjects in report.items():
print(name, sum(subjects.values()))
Example: phone book search
phone_book = {"asha": "98765 43210", "ravi": "91234 56780"}
name = input("Search name: ").strip().lower()
print(phone_book.get(name, "Not found"))
Common mistakes
- Reading a missing key with
d[key]and getting aKeyError; useget()when the key may be missing. - Expecting to find a value with
in:91 in studentchecks the keys, not the values. Use91 in student.values(). - Using a list as a key:
TypeError: unhashable type: 'list'. - Changing the size of a dictionary while looping over it.
Key points
- A dictionary stores
key: valuepairs; keys are unique. d[k] = vadds or updates;delandpopremove.- Loop with
items()to get keys and values together. d.get(k, 0) + 1is the standard counting pattern.
Practice questions
1. What does {"a": 1, "a": 2} become?
{"a": 2}. Keys are unique, so the second value replaces the first.
2. Count the letters in the word "banana".
count = {}
for ch in "banana":
count[ch] = count.get(ch, 0) + 1
print(count) # {'b': 1, 'a': 3, 'n': 2}3. Print every item from prices that costs more than Rs 12.
for item, price in prices.items():
if price > 12:
print(item)4. What is the difference between d["x"] and d.get("x") when "x" is missing?
d["x"] raises a KeyError; d.get("x") returns None (or the default you give).
5. From a list of student dictionaries, make a list of only the names.
names = [s["name"] for s in students]