Lesson 10 / 1191%

Lesson 10

Dictionaries

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.

What is a dictionary?

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.

dictionary.py
person = {
    "last_name": "Dupont",
    "first_name": "Léa",
    "age": 25,
    "city": "Lyon",
}

print(person["first_name"])   # Léa
print(len(person))            # 4
Screenshot: a terminal showing the result of running the dictionary.py script, with the two messages displayed one below the other.

The rules for keys

  • A key is unique: if you write the same key twice, the last value replaces the first.
  • A key is immutable: most often you use strings ("name") or numbers, sometimes tuples, but never lists.
  • Values are free: text, number, boolean, list, and even another dictionary.

Reading, adding and modifying

modify_dict.py
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.

Testing and merging

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.

dict_tools.py
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)                 # 10

Going through a dictionary

  • keys(): all the keys.
  • values(): all the values.
  • items(): the (key, value) pairs.
dict_traversal.py
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")

Nested dictionaries

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.

nested.py
user = {
    "name": "Léa",
    "address": {
        "city": "Lyon",
        "postal_code": "69000",
    },
    "languages": ["Python", "HTML"],
}

print(user["address"]["city"])   # Lyon
print(user["languages"][0])      # Python

Combining lists and dictionaries

Data 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.

list_of_dicts.py
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)}")
Screenshot: a terminal showing the result of running the list_of_dicts.py script, with the messages displayed one below the other.

List, tuple or dictionary?

  • List: an ordered sequence of elements that you want to modify.
  • Tuple: an ordered sequence that must never change.
  • Dictionary: data described by names (keys) rather than by positions.

Common errors

  • Reading a missing key:d["x"]causes aKeyErrorif the key doesn’t exist. Preferd.get("x").
  • Forgetting the quotation marks on keys:person[name]looks for a variable namedname, whereasperson["name"]looks for the text key.
  • Using a list as a key: a list is mutable, so it causes aTypeError.
  • Adding or removing keys while looping over the dictionary: this causes aRuntimeError. Loop over a copy instead, or build a new dictionary.

Exercise

Create a dictionary representing a book (title, author, year, number of pages). Display each piece of information with a loop, then add an “available” key with the valueTrue. Finally, useget()to display a key that doesn’t exist, with a default message.

Going further

Write a program that counts how many times each letter appears in a word entered by the user, storing the results in a dictionary (hint: useget()with 0 as the default). Then display the most frequent letter.