Sub topic 1
A quick refresher on lists and dictionaries
Nested data is built from two containers: the list and the dictionary. Every later chapter combines them, so this chapter reviews the operations you will use most and the behaviors that matter once you nest them.
Prerequisites
This chapter assumes you can already do the following:
- Write basic Python syntax and assign variables.
- Create a list and read items by index.
- Create a dictionary and look up a value by key.
- Write a
forloop and a simple function.
If any of these is unfamiliar, review it first. The chapter is a refresher, not an introduction.
Lists: ordered and changeable
A list is an ordered sequence of items. You read items by position, starting at 0. Negative indexes count from the end.
fruits = ["apple", "pear", "kale"]
print(fruits[0]) # apple
print(fruits[-1]) # kale
print(fruits[:2]) # ['apple', 'pear']
fruits.append("fig")
fruits[1] = "plum"
print(fruits) # ['apple', 'plum', 'kale', 'fig']
last = fruits.pop()
print(last) # fig
print(len(fruits)) # 3A list is mutable, which means you can change it after you create it. append(), pop(), and assignment to an index all change the existing list instead of making a new one.
Reading an index that does not exist raises an IndexError. A list with three items has valid indexes 0, 1, 2 (and -1, -2, -3).
Dictionaries: keys that point to values
A dictionary maps keys to values. You read a value by key instead of by position. Keys must be hashable, so strings, numbers, and tuples work as keys, but lists do not. Dictionaries keep the order in which keys were inserted.
person = {"name": "Ana", "age": 31}
print(person["name"]) # Ana
person["age"] = 32 # update an existing key
person["city"] = "Lima" # add a new key
del person["city"] # remove a key
print(person.get("email")) # None
print("name" in person) # True
for key, value in person.items():
print(key, value)
# name Ana
# age 32The same square-bracket syntax reads, updates, and adds a key. Whether it updates or adds depends on whether the key already exists.
Reading a missing key with person["email"] raises a KeyError. The get() method returns None instead, or a default value that you pass as the second argument. The in operator tests whether a key exists.
What a dictionary iterates over
A plain for loop over a dictionary gives you its keys. Use values() for the values and items() for key and value pairs together. You will use items() often once dictionaries hold other dictionaries.
scores = {"Ana": 90, "Ben": 70}
print(list(scores)) # ['Ana', 'Ben']
print(list(scores.values())) # [90, 70]
print(list(scores.items())) # [('Ana', 90), ('Ben', 70)]Variables hold references
Both containers are mutable, and a variable holds a reference to the object, not a copy of it. Assigning one variable to another gives you two names for the same object.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
print(a is b) # TrueWith flat data this is easy to overlook. With nested data it causes real bugs, because an inner list or dictionary can be reachable from several places. A later chapter covers shared references and copying in detail. For now, remember that b = a does not copy anything.
Putting it together
Nesting means that a list item or a dictionary value is itself a list or a dictionary. Every skill above still applies at each level. You index into a list, look up a key in a dictionary, and watch for IndexError and KeyError.
Common errors to recognize
| Error | Typical cause | Quick fix |
|---|---|---|
| `IndexError` | Index is outside the list's range | Check `len()` first, or use a valid index |
| `KeyError` | Key is not in the dictionary | Use `get()` or test with `in` |
| `TypeError: unhashable type` | A list used as a dictionary key | Use a tuple or a string instead |
| Surprise changes in another variable | Two names refer to the same object | Copy the object on purpose |
Exercise
Given data = {"scores": [80, 90]} and alias = data, you run alias["scores"].append(100). What does data["scores"] contain, and why?
Show answer
It contains [80, 90, 100]. The assignment alias = data does not copy the dictionary. Both names refer to the same dictionary, so a change made through alias is visible through data.
Exercise
A dictionary d has the key "a" but not the key "b". What do d.get("b", 0) and d["b"] do?
Show answer
d.get("b", 0) returns 0 because "b" is missing and 0 is the default. d["b"] raises a KeyError.