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.
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.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details:
print(i)
We can pass the key to the dictionary variable in square brackets to get the value.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details:
print(emp_details[i])
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.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.items():
print(i)
We can use the tuple unpacking approach to unpack the tuple.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for j,k in emp_details.items():
print(j,k)
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.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.keys():
print(i)
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.
emp_details = {'first_name':'Tim', 'last_name':'Cook', 'emp_id':200, 'bill':200.20}
for i in emp_details.values():
print(i)
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.
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)
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.
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}")
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.
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)
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.
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)
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.
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)