Dictionaries
A dictionary stores pairs: each key maps to a value. You look up a value by its key instead of its position.
Making a dictionary
Use curly braces with key: value pairs separated by commas.
scores = {"Alice": 30, "Bob": 55}print(scores)This prints {'Alice': 30, 'Bob': 55}. The names are keys; the scores are values. Use {} for an empty dictionary.
Looking up a value
Put the key in square brackets to read its value.
scores = {"Alice": 30, "Bob": 55}print(scores["Alice"])This prints 30. Looking up a missing key raises KeyError.
Check whether a key exists
in and not in check dictionary keys, not values. Check a key before reading it when it might be missing.
colours = {"sky": "blue", "grass": "green"}print("sky" in colours)print("blue" in colours)name = "sand"if name in colours: print(colours[name])else: print("No colour recorded")This prints True, False, then No colour recorded. The check avoids looking up the missing key "sand".
Updating and counting
Assign to a key to add a new entry or replace its value. To increase a stored score or count, read its value, add to it, and assign it back.
scores = {"Alice": 30, "Bob": 55}scores["Bob"] = scores["Bob"] + 5scores["Cara"] = 10print(scores)This prints {'Alice': 30, 'Bob': 60, 'Cara': 10}. Bob's entry changes; Cara's entry is added at the end.
Looping over keys
A for loop visits dictionary keys in the order you added them. Use each key to read its value.
scores = {"Alice": 30, "Bob": 55}for name in scores: print(name, scores[name])This prints Alice 30, then Bob 55. Updating an existing value keeps its key in the same position.
See also: For loops, Nested data.
Your turn
Add two lines: print Bob's banked amount, then print whether "Cara" is a key in the dictionary.
55 False
banked = {"Alice": 30, "Bob": 55}# add two prints: Bob's amount, then the "Cara" membership checkAdvanced reading
- Dictionary values and totals — read mixed values, count entries and total numeric values.
- Dictionary defaults and counting — use
get()for missing keys and count repeated values. - Accumulator starting values — build a tally from an empty dictionary.
- Dictionary comprehension — build and filter dictionaries in one expression.