How to Iterate Over Dictionaries Using For Loop in Python?

Spread the love

Problem –

You want to iterate over dictionaries using a for loop in Python.

Solution –

Let’s first create a dictionary.

In [1]: person = {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

Now, there are various ways to iterate through a dictionaries using a for loop in python. Let’s look at them one by one.

Looping through all key-value pairs –

To loop through a dictionary in Python, you can use a for loop.

Let’s say I want to get all the information we have stored about Noah.

In [2]: for key, value in person.items():
   ...:     print("\nkey: ", key)
   ...:     print("value: ", value)

key:  Name
value:  Noah

key:  Age
value:  25

key:  Location
value:  New York

To hold the key and the value in each key-value pairs we used two variables in the for loop. You can name these variables anything you want, It’s completely up to you. But try to be informative, which will help others to understand it better. Then in the end of the for loop we write the name of the dictionary followed by the item method which gives the list of key and value in pairs of the dictionary. Then in the body of the for loop we use two print statements to print the key and value of each key-value pair in the dictionary. The “\n” in the first print statement ensures that a new blank line is added before each key-value pair in the output.

Although here we get the key-value pairs in order in the output. It might not always happens as Python does not care about the order in which you stored the key-value pairs in a dictionary. It only care about the individual connection between each key and value of a pair.

Looping through all keys in a dictionary –

If you only want to loop through all the keys of a dictionary then you can use the keys() method.

In [3]: for key in person.keys():
   ...:     print(key)

The first line says pull all the keys from the dictionary and store then in the key variable one at a time. Then in the body of the loop we just print it.

Looping through the keys is the default behavior when we loop through a dictionary. So to loop through a dictionary we can also write.

In [4]: for key in person:
   ...:     print(key)

Looping through all the values in a dictionary –

To loop through all the values in a dictionary we use the values() method.

In [5]: for value in person.values():
   ...:     print(value)
New York

Related Posts –

  1. A Brief Introduction to Dictionaries in Python

Rating: 1 out of 5.

Leave a Reply