Lesson 10
22 min
Map keys to values and combine lists and dictionaries.
Definition
A dictionary (typedict) is a collection of key: value pairs. Eachkey is unique and serves as an identifier to find the associated value, without going through a position. Unlike a list, you access it by a name, for exampleperson["age"]. A dictionary is written between curly braces and it ismutable.
A dictionary stores data as key: valuepairs. Instead of accessing an element by its position as in a list, you access it by its key, the way you look up a word in a real dictionary. It is written between curly braces.
It’s the ideal tool for describing a real-world object: a person, a product, a book. Rather than remembering that the first name is at position 1 in a list, you simply writeperson["first_name"], which makes the code much more readable.
person = {
"last_name": "Dupont",
"first_name": "Léa",
"age": 25,
"city": "Lyon",
}
print(person["first_name"]) # Léa
print(len(person)) # 4
"name") or numbers, sometimes tuples, but never lists.person = {"last_name": "Dupont", "age": 25}
person["age"] = 26 # modify a value
person["email"] = "lea@ex.com" # add a new pair
del person["last_name"] # delete a pair
print(person)
# get() avoids the error if the key doesn't exist
print(person.get("phone", "Not provided"))Good to know
Reading a key that doesn’t exist withperson["phone"]causes aKeyError. Use.get()with a default value, or test first with"phone" in person.
Theinoperator checks for the presence of a key, not a value. Theupdate()method merges one dictionary into another, andpop()removes a key while returning its value.
stock = {"apples": 10, "pears": 4}
print("apples" in stock) # True (we test the keys)
print(10 in stock) # False (10 is a value, not a key)
stock.update({"pears": 6, "kiwis": 12}) # modifies and adds
print(stock) # {'apples': 10, 'pears': 6, 'kiwis': 12}
sold = stock.pop("apples") # removes the key and returns its value
print(sold) # 10keys(): all the keys.values(): all the values.items(): the (key, value) pairs.prices = {"apple": 1.2, "banana": 0.8, "cherry": 4.5}
for fruit, price in prices.items():
print(f"{fruit} costs {price} euros per kilo")
total = sum(prices.values())
print(f"One kilo of each: {total} euros")A value can itself be a dictionary, which lets you describe richer data. To reach a deeply nested value, you chain the keys between square brackets.
user = {
"name": "Léa",
"address": {
"city": "Lyon",
"postal_code": "69000",
},
"languages": ["Python", "HTML"],
}
print(user["address"]["city"]) # Lyon
print(user["languages"][0]) # PythonData structures combine easily. A list of dictionaries is a very common way to represent data, like the rows of a table: it’s also the format you will encounter in most web APIs.
students = [
{"name": "Léa", "grade": 15},
{"name": "Tom", "grade": 12},
{"name": "Sara", "grade": 18},
]
for student in students:
print(f"{student['name']}: {student['grade']}/20")
grades = [s["grade"] for s in students]
print(f"Average: {sum(grades) / len(grades)}")
d["x"]causes aKeyErrorif the key doesn’t exist. Preferd.get("x").person[name]looks for a variable namedname, whereasperson["name"]looks for the text key.TypeError.RuntimeError. Loop over a copy instead, or build a new dictionary.Exercise
True. Finally, useget()to display a key that doesn’t exist, with a default message.Going further
get()with 0 as the default). Then display the most frequent letter.