3. Storing data in lists and dictionaries

A schedule rarely consists of just one course, and an expense claim rarely of just one receipt. As soon as you work with more than a few values, you want to store them under one name, be able to search them and be able to change them. Python has two types for this that you will come across in almost every script: the list for a series of similar values, and the dictionary for the details of one item. Together they are the usual way to hold a table in Python.

Learning objectives

After this chapter:

  • You create a list, retrieve values from it and modify it.
  • Do you know the difference between sort() en sorted().
  • You create a dictionary with keys and values, and add something to it.
  • To retrieve a value safely, use get().
  • You build a list of dictionaries and look up a value in it.

The list: a series of values under one name

You create a list with square brackets, and you separate the values with commas. The order in which you put them in is preserved, and the same value can appear more than once. The indexing and slicing from chapter 2 work in exactly the same way here, except that you now get whole values back instead of individual characters.

list.py

cursussen = ["Python basis", "SQL basis", "Excel gevorderd"]
print(cursussen)
print(len(cursussen))
print(cursussen[0])
print(cursussen[-1])
print(cursussen[1:])

Output

['Python basis', 'SQL basis', 'Excel gevorderd']
3
Python basis
Excel gevorderd
['SQL basis', 'Excel gevorderd']

A list is mutable. With append() zet je er een waarde achteraan, met een index en een isteken vervang je een waarde, en met remove() haal je een waarde weg. Met het woord in vraag je of een waarde erin zit; dat geeft True of False.

list.py

cursussen = ["Python basis", "SQL basis", "Excel gevorderd"]
cursussen.append("Power BI basis")
cursussen[1] = "SQL gevorderd"
cursussen.remove("Excel gevorderd")
print(cursussen)
print("Python basis" in cursussen)

Output

['Python basis', 'SQL gevorderd', 'Power BI basis']
True

If you ask for a position that does not exist, Python stops. A list with three courses has positions 0, 1 and 2:

list.py

cursussen = ["Python basis", "SQL basis", "Excel gevorderd"]
print(cursussen[3])

Output

Traceback (most recent call last):
  File "/tmp/cursus/lijst.py", line 2, in <module>
    print(cursussen[3])
          ~~~~~~~~~^^^
IndexError: list index out of range

The bottom line says it all: the index is outside the list. If you want the last element, use cursussen[-1]. Dat werkt ook als de lijst later langer of korter wordt.

Sorting with sort() and sorted()

You want to show a schedule in a fixed order: by name, or from cheapest to most expensive. Python has two tools for this that look alike but do different things. The method sort() sorteert de lijst zelf; de oude volgorde is daarna weg. De ingebouwde functie sorted() laat de lijst met rust en geeft een nieuwe, gesorteerde lijst terug. Met reverse=True sorteer je van hoog naar laag.

sorteren.py

cursussen = ["Python basis", "SQL basis", "Excel gevorderd"]
cursussen.sort()
print(cursussen)

prijzen = [995.0, 525.0, 1495.0]
op_prijs = sorted(prijzen)
print(op_prijs)
print(prijzen)
print(sorted(prijzen, reverse=True))

Output

['Excel gevorderd', 'Python basis', 'SQL basis']
[525.0, 995.0, 1495.0]
[995.0, 525.0, 1495.0]
[1495.0, 995.0, 525.0]

The list prijzen staat na sorted() nog in de oude volgorde. Dat is handig als je de oorspronkelijke volgorde nog nodig hebt, bijvoorbeeld omdat die de volgorde van invoer is.

Tip

sort() geeft niets terug, in Python heet dat None. Schrijf je cursussen = cursussen.sort(), dan gooi je je lijst weg en houd je None over:

sorteren.py

cursussen = ["Python basis", "SQL basis", "Excel gevorderd"]
cursussen = cursussen.sort()
print(cursussen)
print(cursussen[0])

Output

None
Traceback (most recent call last):
  File "/tmp/cursus/sorteren.py", line 4, in <module>
    print(cursussen[0])
          ~~~~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

The message says that you from None geen element kunt opvragen. Je laat de toekenning weg (alleen cursussen.sort()), of je schrijft cursussen = sorted(cursussen).

The dictionary: a value with a name

A course has a name, a number of days, a price and a maximum number of participants. If you put those four values in a list, you have to remember yourself that position 2 is the price. A dictionary solves that: you give each value a name. Such a name is called a key, and together with the value it forms a key-value pair. You write a dictionary with curly brackets, a colon between key and value, and commas between the pairs.

dict.py

cursus = {"naam": "Python basis", "dagen": 3, "prijs": 1495.00, "max_deelnemers": 12}
print(cursus["naam"])
print(cursus["prijs"])

cursus["prijs"] = 1595.00
cursus["locatie"] = "Amsterdam"
print(len(cursus))
print(cursus)

Output

Python basis
1495.0
5
{'naam': 'Python basis', 'dagen': 3, 'prijs': 1595.0, 'max_deelnemers': 12, 'locatie': 'Amsterdam'}

You retrieve a value by putting the key in square brackets. This is similar to an index, but you use the name instead of a position. Assigning to a key that already exists overwrites the value: the price is now 1595. Assigning to a key that does not exist yet adds a new pair: the location. len() telt het aantal paren. De volgorde waarin je de paren toevoegde, blijft bewaard, dus locatie staat achteraan.

Tip

The rule of thumb: use a dictionary when the elements are different in nature (a name, a quantity, an amount), and a list when they are similar (three course names in a row). That keeps your code readable, including for whoever maintains it after you.

Retrieving values safely with get() and looping through everything with items()

Keys are case-sensitive. If you request a key that does not exist, Python stops with a KeyError:

dict.py

cursus = {"naam": "Python basis", "dagen": 3, "prijs": 1495.00}
print(cursus["Naam"])

Output

Traceback (most recent call last):
  File "/tmp/cursus/dict.py", line 2, in <module>
    print(cursus["Naam"])
          ~~~~~~^^^^^^^^
KeyError: 'Naam'

If you are not sure whether a key exists, you have two options. With in vraag je het eerst. Met get() vraag je de waarde op zonder risico: bestaat de sleutel niet, dan krijg je None, of de standaardwaarde die je als tweede meegeeft. Wil je alle paren langslopen, dan gebruik je een for-lus met items(). Die geeft per ronde een sleutel en een waarde, die je in twee namen opvangt. De for-lus komt in hoofdstuk 4 uitgebreid aan bod; hier zie je hem alvast in zijn eenvoudigste vorm. De regel die herhaald wordt, staat ingesprongen onder de regel met de dubbele punt.

dict.py

cursus = {"naam": "Python basis", "dagen": 3, "prijs": 1495.00}
print("prijs" in cursus)
print(cursus.get("locatie"))
print(cursus.get("locatie", "onbekend"))

for sleutel, waarde in cursus.items():
    print(f"{sleutel}: {waarde}")

Output

True
None
onbekend
naam: Python basis
dagen: 3
prijs: 1495.0

A list of dictionaries

Now that each course is a dictionary, you combine both types. The schedule becomes a list, and each element of that list is a dictionary. This structure within a structure is the standard way to hold tabular data in Python: the list determines the order (the rows), and the dictionary determines the meaning of each piece of data (the columns).

rooster.py

rooster = [
    {"naam": "Python basis", "dagen": 3, "prijs": 1495.00},
    {"naam": "SQL basis", "dagen": 2, "prijs": 995.00},
    {"naam": "Excel gevorderd", "dagen": 1, "prijs": 525.00},
]

print(rooster[1])
print(rooster[1]["naam"])

for cursus in rooster:
    print(f"{cursus['naam']:<16} {cursus['dagen']} dagen   EUR {cursus['prijs']:>8.2f}")

Output

{'naam': 'SQL basis', 'dagen': 2, 'prijs': 995.0}
SQL basis
Python basis     3 dagen   EUR  1495.00
SQL basis        2 dagen   EUR   995.00
Excel gevorderd  1 dagen   EUR   525.00

A line such as rooster[1]["naam"] lees je van links naar rechts. rooster[1] levert de tweede dictionary op, die van SQL basis. Daarvan vraag je de sleutel "naam" op. In de for-lus heet elke dictionary om de beurt cursus, en daar vraag je de drie gegevens van op.

A frame rooster, a list, with three cards rooster[0], rooster[1] and rooster[2]. Each card is a dictionary with the keys naam, dagen and prijs. For rooster[1], the line naam: SQL basis is circled. At the bottom: rooster[1]["naam"] returns SQL basis.
First the position in the list, then the key in the dictionary.

The f-string contains two new things. Inside an f-string enclosed in double quotation marks, you write the key with single ones: cursus['naam']. Vanaf Python 3.12 mag het ook met dubbele, maar in oudere versies geeft dat een SyntaxError; met enkele werkt het overal. En achter de dubbele punt staat opmaak: :<16 maakt de naam zestien tekens breed en lijnt hem links uit, :>8.2f zet het bedrag rechts uitgelijnd in acht tekens met twee decimalen. Zo komen de kolommen recht onder elkaar. Dat er "1 dagen" staat, los je in hoofdstuk 4 op.

Adding a key to each course while also keeping a running total can be done in the same loop. You start with totaal = 0 vóór de lus en telt er in elke ronde de prijs bij op:

rooster.py

rooster = [
    {"naam": "Python basis", "dagen": 3, "prijs": 1495.00},
    {"naam": "SQL basis", "dagen": 2, "prijs": 995.00},
    {"naam": "Excel gevorderd", "dagen": 1, "prijs": 525.00},
]

totaal = 0
for cursus in rooster:
    cursus["max_deelnemers"] = 12
    totaal = totaal + cursus["prijs"]

print(rooster[1])
print(f"Totale waarde: {totaal:.2f}")

Output

{'naam': 'SQL basis', 'dagen': 2, 'prijs': 995.0, 'max_deelnemers': 12}
Totale waarde: 3015.00
Example

Fatima works in the finance department and receives a list of expense claims every month. She wants to know how much needs to be paid out per colleague. Each claim is a dictionary, and the whole month is a list. She builds up the total per person in a second dictionary, with the name as the key:

declaraties.py

declaraties = [
    {"naam": "Fatima", "soort": "trein", "bedrag": 23.40},
    {"naam": "Joost", "soort": "lunch", "bedrag": 14.75},
    {"naam": "Fatima", "soort": "parkeren", "bedrag": 9.50},
    {"naam": "Joost", "soort": "trein", "bedrag": 31.20},
]

per_persoon = {}
for d in declaraties:
    naam = d["naam"]
    per_persoon[naam] = per_persoon.get(naam, 0) + d["bedrag"]

print(per_persoon)
for naam, bedrag in per_persoon.items():
    print(f"{naam}: {bedrag:.2f} euro")

Output

{'Fatima': 32.9, 'Joost': 45.95}
Fatima: 32.90 euro
Joost: 45.95 euro

The trick lies in per_persoon.get(naam, 0). Bij de eerste declaratie van Fatima bestaat de sleutel "Fatima" nog niet, dus geeft get() 0, en daar komt 23.40 bij. Bij haar tweede declaratie geeft get() 23.40, en daar komt 9.50 bij. Zonder get() had de eerste ronde een KeyError gegeven. Fatima krijgt 32.90 euro (23.40 + 9.50), Joost 45.95 (14.75 + 31.20).

The first print() toont 32.9 en niet 32.90: een float laat de nul aan het eind weg. Daarom staat er in de nette regels :.2f. Met precies dezelfde vijf regels tel je omzet per klant, uren per project of verkopen per vestiging, zolang de gegevens als lijst van dictionaries binnenkomen.

Exercise

You create a list of dictionaries for something from your own work, with at least three rows and three keys: for example projects with name, hours and rate, or items with name, quantity and price.

  • You print the whole second row, and then only the name from the last row (using -1).
  • You add a fourth key to each row, for example a status.
  • You calculate a total over all rows in a for loop and display it with two decimal places.
  • You ask with get() een sleutel op die niet bestaat, met een standaardwaarde.

If you get a KeyError, dan kijk je naar de schrijfwijze van de sleutel in de onderste regel: een hoofdletter of een spatie verschil is genoeg.

Lists and dictionaries at a glance

  • You create a list with square brackets. It keeps its order and can be changed: append(), remove(), een nieuwe waarde op een index.
  • Counting starts at 0; a position that does not exist gives an IndexError.
  • sort() sorteert de lijst zelf en geeft None; sorted() geeft een nieuwe lijst.
  • You create a dictionary with curly brackets and key-value pairs. You look things up by key, not by position.
  • An unknown key gives a KeyError; get() geeft dan None of je standaardwaarde.
  • A list of dictionaries is a table: the list is the rows, the keys are the columns.
Knowledge check

What shows print(cursussen) na cursussen = cursussen.sort()?

The dictionary cursus heeft geen sleutel "locatie". Wat geeft cursus.get("locatie", "onbekend")?

What does this return rooster[0]["prijs"] bij het rooster uit dit hoofdstuk?

Share this chapter: