Learn
03.4 | DICTIONARIES AND KEY-VALUE DATA
01 | NAMED FIELDS MAKE A RECORD CLEAR
A list such as ["Maya", 8] requires you to remember that position zero means name and one means score. A dictionary can name those meanings directly.
A dictionary stores key-value pairs. In {"name": "Maya", "score": 8}, "name" and "score" are keys; their associated values are Maya and eight. A colon joins each pair and commas separate pairs.
Use keys to retrieve values. A dictionary is a mapping, not a sequence selected by a position. The key can be a string describing the value’s role.
player = {"name": "Maya", "score": 8}
print(player["name"])
print(player["score"])EXPECTED OUTPUT
Maya 8
02 | KEYS AND VALUES DO DIFFERENT JOBS
A key identifies an entry within that dictionary. The value is the data associated with it. player["score"] is lookup using the key score, not a search for a value that happens to be eight.
Keys must be unique. Assigning another value under the same key updates that entry rather than adding a second entry with an identical key. Values can repeat under different keys.
Keys are case-sensitive when strings: "score" and "Score" are different. Use consistent field naming in related records.
03 | UPDATE OR ADD AN ENTRY
Dictionaries are mutable. player["score"] = 10 changes the existing score entry. player["level"] = "beginner" adds a new entry if that key was absent.
The collection’s length counts entries, not separate keys plus values. A dictionary with name, score and level has three entries.
A second name assigned to the dictionary aliases the same mutable object. A dictionary copy makes a new outer mapping but remains shallow when its values contain mutable objects.
player = {"name": "Maya", "score": 8}
player["score"] = 10
player["level"] = "beginner"
print(len(player))
print(player["score"])EXPECTED OUTPUT
3 10
04 | A MISSING KEY IS NOT AN EMPTY VALUE
player["team"] raises KeyError if team does not exist. That is different from an existing team entry whose value is an empty string or None.
Use membership with in when you need to check whether a key exists. "team" in player tests keys, not values. A conditional lookup can then provide a clear absence message.
player = {"name": "Maya", "score": 8}
if "team" in player:
print(player["team"])
else:
print("No team recorded")EXPECTED OUTPUT
No team recorded
05 | GET PROVIDES A DEFAULT
player.get("team", "Unassigned") returns the stored value if team exists, or the supplied default if absent. It does not insert a team entry.
Without an explicit default, get returns None for a missing key. If an existing key’s value is None, the result can look the same, so use membership when that distinction matters.
Do not treat a legitimate zero score as missing. Checking if player.get("score") uses truthiness; zero is falsy even when the key exists.
player = {"name": "Maya", "score": 0}
print(player.get("team", "Unassigned"))
print("score" in player)
print(player["score"])EXPECTED OUTPUT
Unassigned True 0
06 | ITERATE OVER KEYS OR PAIRS
for key in player iterates over keys. player.values() supplies values; player.items() supplies key-value pairs. With items, unpack the pair into two names.
Current Python dictionaries preserve insertion order, but that does not turn them into positional lists. player[0] means lookup of an integer key zero, not “retrieve the first entry”.
Changing an existing value does not move its key to the end. Adding or deleting keys while iterating over the dictionary can raise RuntimeError, so gather intended changes or iterate over a suitable copy instead.
player = {"name": "Maya", "score": 8}
for key, value in player.items():
print(key, "=", value)EXPECTED OUTPUT
name = Maya score = 8
07 | REMOVE AN ENTRY DELIBERATELY
del player["level"] removes a key-value entry and raises KeyError if the key is absent. pop(key) removes and returns its associated value; a default argument can supply an absence result.
Deletion changes the mapping. get only retrieves and does not delete. Choose the operation matching the required action rather than expecting every method to mutate.
player = {"name": "Maya", "score": 8, "level": "beginner"}
removed = player.pop("level")
print(removed)
print("level" in player)EXPECTED OUTPUT
beginner False
08 | KEYS MUST BE HASHABLE
String and integer keys are common. Suitable tuples can also be keys, but lists, sets and dictionaries cannot be ordinary dictionary keys because they are unhashable.
The key need not be text, yet its meaning should remain clear. An integer key such as 101 can identify a record; it is not automatically a positional index.
Values have no equivalent hashable-only restriction. A value can be a list, another dictionary or other data, which lets dictionaries describe richer records.
09 | ONE RECORD IS NOT THE WHOLE DATABASE
A player dictionary can represent one record. A list of such dictionaries can represent several records. Keeping a player’s name and score inside the same dictionary preserves their relationship when processing the list.
A dictionary key’s uniqueness applies within that mapping. A field named "id" in each separate record does not automatically enforce uniqueness across the whole list. That is a separate program or database rule.
For simple flat records, choose consistent keys and expected value types. This makes later loops easier to understand and test.
10 | TRY LOOKUP, UPDATE AND DEFAULTS
The demo starts with name = Maya and score = 8. Look up a field or update the score. Missing fields show the difference between strict lookup and a default result. Field names are case-sensitive.
11 | BUILD A SMALL PLAYER RECORD
Create a dictionary with name, score and completed. Print a report by looking up those keys. Update the score and add a team field, then show its new entry count.
Test a score of zero and a missing optional team. Explain why membership is the right way to distinguish an absent score from an existing zero score.
Extension: display all pairs using items, then make a shallow copy and change one flat numeric value in the copy. Compare this with aliasing the original.
PUT YOUR SKILLS TO WORK
Use the Section 3 challenges to practise these ideas independently. Work in your Python editor, predict results and keep a short test record.
Section 3 challenges Python course navigation