Open In App

Iterate over a dictionary in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In this article, we will cover How to Iterate Through a Dictionary in Python. Dictionary in Python is a collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair in Python

To Iterate through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys.

Python Dictionaries

Dictionaries in Python are very useful data structures. Dictionaries store items in key-value pairs.

Dictionary keys are hashable type, meaning their values don’t change in a lifetime. There can not be duplicate keys in a dictionary.

To access the value stored in a Python dictionary you have to use keys.

How to Iterate Through a Dictionary in Python

Iterating through a dictionary means, visiting each key-value pair in order. It means accessing a Python dictionary and traversing each key-value present in the dictionary. Iterating a dictionary is a very important task if you want to properly use a dictionary.

There are multiple ways to iterate through a dictionary, we are discussing some generally used methods for dictionary iteration in Python which are the following:

  • Iterate Python dictionary using build.keys() 
  • Iterate through all values using .values()
  • Looping through Python Dictionary using for loop
  • Iterate key-value pair using items()
  • Access key Using map() and dict.get
  • Access key in Python Using zip()
  • Access key Using Unpacking of Dict

Note: In Python version 3.6 and earlier, dictionaries were unordered. But since Python version 3.7 and later, dictionaries are ordered.

Iterating Dictionary in Python using .values() method

To iterate through all values of a dictionary in Python using .values(), you can employ a for loop, accessing each value sequentially. This method allows you to process or display each individual value in the dictionary without explicitly referencing the corresponding keys.

Example: In this example, we are using the values() method to print all the values present in the dictionary.

Python3




# create a python dictionary
statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
print('List Of given capitals:\n')
 
for capital in statesAndCapitals.values():
    print(capital)


Output:

List Of given capitals:
Gandhinagar
Mumbai
Jaipur
Patna

Access Dictionary keys in Python Using the build .keys() 

In Python, accessing the keys of a dictionary can be done using the built-in `.keys()` method. It returns a view object that displays a list of all the keys in the dictionary. This view can be used directly or converted into a list for further manipulation.

Example: In this example, the below code retrieves all keys from the `statesAndCapitals` dictionary using `.keys()` and prints the resulting view object.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
keys = statesAndCapitals.keys()
print(keys)


Output:

dict_keys(['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar'])

Looping through Python Dictionary using for loop

To access keys in a dictionary without using the `keys()` method, you can directly iterate over the dictionary using a for loop, like `for key in my_dict:`. This loop automatically iterates over the keys, allowing you to access each key directly without the need for an explicit method call.

Example: In this example, we are Iterating over dictionaries using ‘for’ loops for iterating our keys and printing all the keys present in the Dictionary.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
print('List Of given states:\n')
 
# Iterating over keys
for state in statesAndCapitals:
    print(state)


Output:

List Of given states:
Gujarat
Maharashtra
Rajasthan
Bihar

Iterate through a dictionary using items() method

You can use the built-in items() method to access both keys and items at the same time. items() method returns the view object that contains the key-value pair as tuples. 

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
 
for key, value in statesAndCapitals.items():
    print(f"{key}: {value}")


Output:

Gujarat: Gandhinagar
Maharashtra: Mumbai
Rajasthan: Jaipur
Bihar: Patna

Iterating Python Dictionary Using map() and dict.get

The method accesses keys in a dictionary using `map()` and `dict.get()`. It applies the `dict.get` function to each key, returning a map object of corresponding values. This allows direct iteration over the dictionary keys, efficiently obtaining their values in a concise manner.

Example: In this example, the below code uses the `map()` function to create an iterable of values obtained by applying the `get` method to each key in the `statesAndCapitals` dictionary. It then iterates through this iterable using a `for` loop and prints each key.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
map_keys = map(statesAndCapitals.get, statesAndCapitals)
for key in map_keys:
    print(key)


Output :

Gandhinagar
Mumbai
Jaipur
Patna

Iterate Python Dictionary using zip() Function

Using `zip()` in Python, you can access the keys of a dictionary by iterating over a tuple of the dictionary’s keys and values simultaneously. This method creates pairs of keys and values, allowing concise iteration over both elements.

Example: In this example, the zip() function pairs each state with its corresponding capital, and the loop iterates over these pairs to print the information

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
for state, capital in zip(statesAndCapitals.keys(), statesAndCapitals.values()):
    print(f'The capital of {state} is {capital}')


Output :

The capital of Gujarat is Gandhinagar
The capital of Maharashtra is Mumbai
The capital of Rajasthan is Jaipur
The capital of Bihar is Patna

Dictionary iteration in Python by unpacking the dictionary

To access keys using unpacking of a dictionary, you can use the asterisk (*) operator to unpack the keys into a list or another iterable.

Example: In this example, you will see that we are using * to unpack the dictionary. The *dict method helps us to unpack all the keys in the dictionary.

Python3




statesAndCapitals = {
    'Gujarat': 'Gandhinagar',
    'Maharashtra': 'Mumbai',
    'Rajasthan': 'Jaipur',
    'Bihar': 'Patna'
}
keys = [*statesAndCapitals]
values = '{Gujarat}-{Maharashtra}-{Rajasthan}-{Bihar}'.format(*statesAndCapitals, **statesAndCapitals)
print(keys)
print(values)


Output:

['Gujarat', 'Maharashtra', 'Rajasthan', 'Bihar']
Gandhinagar-Mumbai-Jaipur-Patna

Iterating through the dictionary is an important task if you want to access the keys and values of the dictionary. In this tutorial, we have mentioned several ways to iterate through all items of a dictionary. Important methods like values(), items(), and keys() are mentioned along with other techniques.



Last Updated : 05 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads