Ways to Loop a Dictionary in Python


Loop a Dictionary

As the dictionary stores data as a key-value pair, we do not loop a dictionary in the way we loop other data structures. Let us discuss ways we can iterate through a dictionary in Python.

Loop a Dictionary

Using for Loop

We can use the for loop to loop through the items of the dictionary.

When using the for loop, it will return the key of the dictionary.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details:
    print(i)
first_name
last_name
emp_id
bill

We can pass the key to the dictionary variable in square brackets to get the value.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details:
    print(emp_details[i])
Tim
Cook
200
200.2

Using for loop with items()

We can use a for loop with the items() method. Every iteration will fetch a tuple of key and its corresponding value. This is one of the easiest ways in case we need a key and the value of the tuple.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.items():
    print(i)
('first_name', 'Tim')
('last_name', 'Cook')
('emp_id', 200)
('bill', 200.2)

We can use the tuple unpacking approach to unpack the tuple.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for j,k in emp_details.items():
    print(j,k)
first_name Tim
last_name Cook
emp_id 200
bill 200.2

Using for loop with keys()

We can also use a for loop with the keys() method, it will return the key of each key-value pair. It brings the same result if we specify the keys or not. Here we are just explicitly specifying that we need keys.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.keys():
    print(i)
first_name
last_name
emp_id
bill

Using for loop with values()

We can also use a for loop with the values() method, it will return the value of each key-value pair. Using this method, we need not refer to the keys while accessing the values.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.values():
    print(i)
Tim
Cook
200
200.2

Using the map() function

The map() function is a built-in function that applies a specified function to all the items in an iterable (such as a list, dictionary) and returns an iterator that produces the results. In this case, we will apply the map function to dict.get. It will apply dict.get to each key in the dictionary and return the value corresponding to that key.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

map_details = map(emp_details.get, emp_details)

for value in map_details:
    print(value)
Tim
Cook
200
200.2

Using the enumerate() function

The enumerate() function is the built-in function used to add a counter to the iterable. It returns the enumerate object. In dictionaries, elements do not have the index position and enumerate is used to add index to the elements.

The enumerate() function has the optional argument “start” to specify the start value.

In [1]:
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}

for i, (key, value) in enumerate(emp_details.items(), start = 1):
    print(f"{i}.) {key} - {value}")
1.) first_name - Tim
2.) last_name - Cook
3.) emp_id - 200
4.) bill - 200.2

Using the dictionary comprehension

Dictionary comprehension is the way to iterate over the existing dictionary to create a new dictionary from the existing one. It gives us the option to custom choose the elements by adding the conditions.

In [1]:
marks = {"Sam": 45, "Steve": 78, "Elon": 88, "Bill": 65, "Tim": 49}

failures = {key:value for key, value in marks.items() if value < 50}
        
print(failures)
{'Sam': 45, 'Tim': 49}

Using the itertools.chain() function

The itertools is the library in Python specially designed for the iterators. The itertools.chain() function can be used with multiple iterators as an argument. It returns a new iterator with elements of iterators passed as arguments.

In [1]:
import itertools

dict1 = {1:"one", 2:"Two"}
dict2 = {3:"Three", 4:"Four"}

for key, value in itertools.chain(dict1.items(), dict2.items()):
    print(key, "-", value)
1 - one
2 - Two
3 - Three
4 - Four

Using the iter() function

The iter() function will return the iterator of the dictionary. It is used with the next() function to fetch the next item from the iterator.

In [1]:
dict1 = {1:"one", 2:"Two", 3:"Three", 4:"Four"}

my_iterator = iter(dict1.items())

for _ in dict1:
    key, value = next(my_iterator)
    print(key, "-", value)
1 - one
2 - Two
3 - Three
4 - Four

References

  1. Iterate over a dictionary in Python