Dictionaries

In this chapter we will work with Python dictionaries. Dictionaries are data structures that indexes values by a given key (key-value pairs). The following example shows a dictionary that indexes students ages by name.

  1. ages = {
  2. "Peter": 10,
  3. "Isabel": 11,
  4. "Anna": 9,
  5. "Thomas": 10,
  6. "Bob": 10,
  7. "Joseph": 11,
  8. "Maria": 12,
  9. "Gabriel": 10,
  10. }
  11. >>> print(ages["Peter"])
  12. 10

It is possible to iterate over the contents of a dictionary using “items”, like this:

  1. >>> for name, age in ages.items():
  2. ... print(name, age)
  3. ...
  4. Peter 10
  5. Isabel 11
  6. Anna 9
  7. Thomas 10
  8. Bob 10
  9. Joseph 11
  10. Maria 12
  11. Gabriel 10

However, dictionary keys don’t necessarily need to be strings but can be any immutable object:

  1. d = {
  2. 0: [0, 0, 0],
  3. 1: [1, 1, 1],
  4. 2: [2, 2, 2],
  5. }
  6. >>> d[2]
  7. [2, 2, 2]

And you can also use other dictionaries as values:

  1. students = {
  2. "Peter": {"age": 10, "address": "Lisbon"},
  3. "Isabel": {"age": 11, "address": "Sesimbra"},
  4. "Anna": {"age": 9, "address": "Lisbon"},
  5. }
  6. >>> students['Peter']
  7. {'age': 10, 'address': 'Lisbon'}
  8. >>> students['Peter']['address']
  9. 'Lisbon'

This is quite useful to structure hierarchical information.

Exercises with dictionaries

Use the Python documentation at https://docs.python.org/3/library/stdtypes.html#mapping-types-dict to solve the following exercises.

Take the following Python dictionary:

  1. ages = {
  2. "Peter": 10,
  3. "Isabel": 11,
  4. "Anna": 9,
  5. "Thomas": 10,
  6. "Bob": 10,
  7. "Joseph": 11,
  8. "Maria": 12,
  9. "Gabriel": 10,
  10. }
  1. How many students are in the dictionary? Search for the “len” function.

  2. Implement a function that receives the “ages” dictionary as parameter and returns the average age of the students. Traverse all items on the dictionary using the “items” method as above.

  3. Implement a function that receives the “ages” dictionary as parameter and returns the name of the oldest student.

  4. Implement a function that receives the “ages” dictionary and a number “n” and returns a new dict where each student is (n) years older. For instance, new_ages(ages, 10) returns a copy of “ages” where each student is 10 years older.

Exercises with sub-dictionaries

Take the following dictionary:

  1. students = {
  2. "Peter": {"age": 10, "address": "Lisbon"},
  3. "Isabel": {"age": 11, "address": "Sesimbra"},
  4. "Anna": {"age": 9, "address": "Lisbon"},
  5. }
  1. How many students are in the “students” dict? Use the appropriate function.

  2. Implement a function that receives the students dict and returns the average age.

  3. Implement a function that receives the students dict and an address, and returns a list with names of all students whose address matches the address in the argument. For instance, invoking “find_students(students, ’Lisbon’)” should return Peter and Anna.