Chapter 4: Dictionaries

Check your understanding

face Josiah Wang

You probably saw this coming - quiz time! (Did you think I’ll let you get away with just reading?)

1 2 3 4 5 6 7 8 9 10 11 12 13

Question 1

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
print(fruit_counts["banana"])

6
Explanation:

You obtain the value of the entry with the key "banana" using square brackets.

Question 2

What is the output of the following code snippet? Type Error if you expect an error.

1
2
3
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
fruit_counts["orange"] += 1
print(fruit_counts["orange"])

4
Explanation:

Line 2 increments fruit_counts["orange"] by 1, making the output 4.

Question 3

What is the output of the following code snippet? Type Error if you expect an error.

1
2
3
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
fruit_counts["orange"] = 1
print(fruit_counts["orange"])

1
Explanation:

Line 2 sets fruit_counts["orange"] to 1. This will also override the existing value (3).

Question 4

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
print(fruit_counts["pineapple"])

Error
Explanation:

You will receive a KeyError: 'pineapple' from Python. As the error message says, fruit_counts does not have "pineapple" as a key.

Question 5

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
print(fruit_counts.get("pineapple", 0))

0
Explanation:

Since "pineapple" is not a key, the .get() method will return the specified default value, which is 0. If you do not provide a default value, then the .get() method will return None (and does not produce any errors).

Question 6

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
fruit_counts["pineapple"] += 1

Error
Explanation:

Error! "pineapple" is not a key in the dictionary, so you cannot retrieve it (and naturally cannot increment it!). You can use fruit_counts["pineapple"] = fruit_counts.get("pineapple", 0) + 1 instead for this to work (if that is your intention!)

Question 7

What is the output of the following code snippet? Type Error if you expect an error.

1
2
3
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
del fruit_counts["apple"]
print(fruit_counts["apple"])

Error
Explanation:

Error! You have already deleted the entry with the key "apple" in Line 2. So it no longer exists in line 3.

Question 8

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
print(len(fruit_counts))

3
Explanation:

The len() function gives you the number of entries in the dictionary.

Question 9

What is the output of the following code snippet? Type Error if you expect an error.

1
2
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
print(list(fruit_counts))

["apple", "orange", "banana"]
Explanation:

You will get the list of keys to the dictionary when you convert a dictionary to a list with list(). You can use the keys in the list to retrieve the values from fruit_counts later. If you use the official Python version 3.6 and above, then the order of the keys in the list will be as how you inserted the keys.

Question 10

What is the output of the following code snippet? Type Error if you expect an error.

1
2
3
fruit_counts = {"apple": 5, "orange": 3, "banana": 6}
for fruit in fruit_counts:
    print(fruit_counts[fruit])

5 3 6
Explanation:

When you iterate over a dictionary using a for loop, you are iterating over its keys. Again, it is possible that Python might give you a different ordering if you are not using the official Python interpreter (version >=3.6).

Question 11

What is the code that should replace ??? in line 4 to retrieve the number of oranges from inventory (the expected output is 3).

1
2
3
4
5
inventory = {"fruits": {"apple": 2, "orange": 3},
             "vegetables": {"lettuce": 4, "spinach": 5}
            }
num_of_oranges = ???
print(num_of_oranges)
inventory["fruits"]["orange"]
Explanation:

Like lists, you can have nested dictionaries (a dictionary inside a dictionary). Accessing the value of an inner dictionary is similar to accessing an inner list. inventory["fruits"] will give you {'apple': 2, 'orange': 3}, and inventory["fruits"]["orange"] will give you 3.

Question 12

What is the output of the following piece of code?

1
2
3
4
cohort_dict = {"ai": ["Rosa", "Lambert", "Kelan"],
               "computing": ["Sarina", "Bartolomeo"]
              }
print(cohort_dict["ai"][2])
Kelan
Explanation:

You can have any object as a value. In this example, the values are lists. Therefore, cohort_dict["ai"] gives you the list ["Rosa", "Lambert", "Kelan"], and cohort_dict["ai"][2] will give you the third element in the list, i.e. "Kelan".

Question 13

What is the output of the following piece of code?

1
2
3
4
5
students = [
            {"name": "Lebogang", "age": 20},
            {"name": "Irene", "age": 19}
           ]
print(students[1]["age"])
19
Explanation:

Lists can have any object as its element, including dictionaries! So here is another common use case for dictionaries. students[1] will give you the second element in the list, that is {"name": "Irene", "age": 19}. And you can retrieve the name of this student with students[1]["name"] and the age with students[1]["age"].