3.2. Looping Through a Dictionary

Dictionaries can be used to store information in a variety of ways and there are several ways for looping through them.

Looping Through All Key-Value Pairs

The following dictionary store a food name, price, and flavor:

You can get any information about food_0 using the method in the previous subsections. Here, we want to see everything stored in this food's dictionary. To do that, we can use the for loop as in this example.

As shown in that example, to write a for loop for dictionary, we make two variable names: one for key and the other one for value. (You can choose any names you want). After that use the method .items() after the variable name. This will return a list of key-value pair.

Let's see another example using dictionary with similar items.

Here we use name and price in the loop instead of key and value. This will make it easier to follow what's happening in the loop.

Looping Through All the Keys in a Dictionary

You can use the keys() method when you don't need to work with the values in a dictionary. We will try to loop through the food name in the food_price dictionary and print all the available food:

Looping through the keys is the default method when using loop through a dictionary. The code from the previous example will still work without using the .keys():

Looping Through All Values in a Dictionary

If you are interested in the values that a dictionary contains, use the values() method to return a list of values. Let's print the variation of prices in our list:

Dictionary and Set

Dictionary is not the only element in Python that uses {}. A set is a collection in which each item is unique, and this also use {}. In both dictionary and set, only the last element of the same name (key) will be taken. See the following example:

Both set and dictionary do not have ordering, unlike list. For example, if you try to take the element with index 1, the following two code will generate error:

Exercise 3.2

  1. Countries
    Make a dictionary containing three languages and the country each language spoken at. One key-value pair might be 'USA': 'English'.

    • Use a loop to print a sentence about each country, such as
      In USA, people speak English.

    • Use a loop to print the name of each language included in the dictionary.

    • Use a loop to print the name of each country included in the dictionary.

2. Do Exercise 3.1 no.2 using for loop.