Pulsars
0 %
Log inSign up

Dictionaries

Iterating over a dictionary and choosing the right structure

Iterating over a dictionary and choosing the right structure

To iterate over all the key/value pairs of a dictionary, you use the items() method in a for loop:

annuaire = {"Sam": "0601020304", "Alex": "0611223344"}
for nom, numero in annuaire.items():
    print(nom, ":", numero)

This program displays each name followed by its number. If you only want the keys, you can write directly for nom in annuaire: (the keys are iterated over by default).

How do you choose between a list and a dictionary?

  • Use a list when order matters and you access elements by their position (a list of grades, a list of students in arrival order).
  • Use a dictionary when you want to quickly retrieve information using an identifier (a name, a code...), without worrying about order (a directory, a stock of products with their prices).

A concrete example combining both: a dictionary associating each student with their list of grades, to calculate their average.

notes_eleves = {
    "Sam": [12, 15, 8],
    "Alex": [18, 16, 14]
}

for eleve, notes in notes_eleves.items():
    moyenne = sum(notes) / len(notes)
    print(eleve, ":", moyenne)

Here, each key (the first name) is associated with a list of grades: the two structures combine naturally. The sum function adds up all the elements of a list of numbers, which simplifies calculating the average.

Remember the key point: list equals order and position, dictionary equals key and direct access.