LEARN PYTHON | Dictionaries And Key-Value Data

Lesson objective

Create dictionaries, retrieve and update values by key, handle missing keys and iterate over named fields without confusing keys with positions.

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

MATCH THE PYTHON TERM TO ITS MEANING

Terminology

Terminology

Dictionary

A mutable mapping from unique keys to values.

Key

An identifier used to retrieve an entry’s value.

Value

The data associated with a key.

Key-value pair

One dictionary entry.

Mapping

A relationship associating keys with values.

Lookup

Retrieving a value using its key.

KeyError

A strict lookup or removal used an absent key.

get()

Retrieves a value or default without adding the missing key.

Default

A fallback result for an absent key.

Membership

in checks the dictionary’s keys.

items()

Supplies key-value pairs for iteration.

values()

Supplies values for iteration.

Insertion order

The order keys were first added, preserved by current Python dicts.

Entry count

The number of key-value pairs.

pop()

Removes and returns a value for a key.

Hashable key

A key with suitable stable hash/equality behaviour.

Record

Related named values describing one item.

Shallow mapping copy

A new outer dictionary retaining references to its values.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe dictionaries?
2. Which describe repeated keys?
3. Which describe missing keys?
4. Which describe zero score?
5. Which describe iteration?
6. Which can be dictionary keys here?
7. Which describe mutability and copying?
8. Which describe named records?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain key versus value.

2. Compare lookup by key with list indexing.

3. Explain get with a default.

4. Explain existing zero versus missing score.

5. Describe iteration with items.

6. Explain dictionary insertion order.

7. Compare a copied record with an alias.

8. Explain ID uniqueness across record dictionaries.

CODE IT | YOUR INDEPENDENT CHALLENGE

Build a player record. Distinguish a missing score from a score of zero and update safely.

Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for Dictionaries And Key-Value Data is coming soon. Complete the matching task and written questions in your exercise book.