Dictionaries: looking things up by name
A list remembers order. A dictionary remembers names.
The thing lists are bad at
Say you are storing one student's marks. With a list you have to remember what each position meant:
marks = [82, 91, 68]
print(marks[1])
91
Ninety-one in what? You have to keep that in your head, or in a comment, and one day you will insert a subject at the front and every position will shift.
A dictionary stores the name alongside the value:
marks = {"maths": 82, "science": 91, "history": 68}
print(marks["science"])
print(marks["history"])
91 68
Curly braces, key: value pairs, commas between. Now the code says what it
means, and the order it was written in stops mattering.
Keys, not positions
marks[1] is meaningless here. There is no "item 1" — there is only
"science".
marks = {"maths": 82, "science": 91}
print(marks[1])
Read the error: KeyError: 1. Python looked for a key called 1 and did not
find one. That is the same shape as list index out of range from the lists
lesson: you asked for something that is not there.
Asking for a key that might not exist
This is where dictionaries bite beginners. A missing key stops your program dead:
marks = {"maths": 82}
print(marks["art"])
If you are not certain a key is there, use .get() instead — it hands back
None rather than stopping:
marks = {"maths": 82}
print(marks.get("art"))
print(marks.get("art", 0))
None 0
That second argument is a fallback: "give me art, or 0 if there is no
art". It is the difference between a program that copes and a program that
crashes at three in the morning.
You can also ask directly:
marks = {"maths": 82, "science": 91}
if "art" in marks:
print("Found art")
else:
print("No art mark yet")
No art mark yet
Note what in checks: keys, not values. 82 in marks is False, even
though 82 is clearly in there.
Adding and changing
Same square brackets, on the left of an =:
marks = {"maths": 82}
marks["art"] = 75 # a key that did not exist — added
marks["maths"] = 88 # a key that did exist — replaced
print(marks)
print(len(marks))
{'maths': 88, 'art': 75}
2There is no separate "add" and "update". Assigning to a key does whichever one applies, which is convenient but means a typo in a key name adds a new entry instead of raising an error. If a value refuses to change, check your spelling first.
Looping over a dictionary
Loop over a dictionary and you get the keys:
marks = {"maths": 82, "science": 91, "history": 68}
for subject in marks:
print(subject)
maths science history
Usually you want both halves, and .items() gives you them together:
marks = {"maths": 82, "science": 91, "history": 68}
for subject, score in marks.items():
print(f"{subject}: {score}")
maths: 82 science: 91 history: 68
Two loop variables, because each item is a pair. This is the line you will write most often.
Doing something useful with it
Everything from the loops lesson still applies — the values are just numbers:
marks = {"maths": 82, "science": 91, "history": 68}
total = 0
for subject, score in marks.items():
if score >= 80:
print(f"{subject} is strong")
total += score
print(f"Average: {total / len(marks)}")
maths is strong science is strong Average: 80.33333333333333
List or dictionary?
The question to ask is: does position mean anything?
Three test scores where first, second and third are different sittings — that is a list. Three subjects where "second" means nothing — that is a dictionary.
Real programs use both together, and that combination is the next lesson's territory: a list of dictionaries is the shape almost all real data arrives in.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes