Open In App

Iterate over a dictionary in Python

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will cover How to Iterate Through a Dictionary in Python.  To Loop 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.

How to Loop Through a Dictionary in Python

There are multiple ways to iterate through a dictionary, depending if you need key, value or both key-value pairs.

Iterate through Value

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.

Python
# create a python dictionary 
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}

# loop over dict values
for val in d.values():
    print(val)


Iterate through keys

In Python, just looping through the dictionary provides you its keys. You can also iterate keys of a dictionary using built-in `.keys()` method.

Python
# create a python dictionary 
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}

# default loooping gives keys
for keys in d:
	print(keys)
    
# looping through keys    
for keys in d.keys():
  print(keys)

Iterate through both keys and values

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. 

Python
# create a python dictionary 
d = {"name": "Geeks", "topic": "dict", "task": "iterate"}

# iterating both key and values
for key, value in d.items():
    print(f"{key}: {value}")


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.

Python
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

Python
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.

Python
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.



Next Article

Similar Reads