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.
# 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.
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.
statesAndCapitals = { 'Gujarat': 'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur', 'Bihar': 'Patna'}print('List Of given states:\n')# Iterating over keysfor 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.
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.
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
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.
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.
- Iterate through a list of dictionaries in Python
- Iterate through value lists dictionary
- How to Iterate over nested dictionary
- Delete items from the dictionary while iterating
Iterate over a dictionary in Python – FAQs
How can we iterate over keys in a Python dictionary?
To iterate over keys in a Python dictionary, you can use the
keys()
method or directly iterate over the dictionary. Here are both methods:# Example dictionary
my_dict = {'a': 1, 'b': 2,, 'c': 3}# Using the keys() method
for key in my_dict.keys():
print(key)# Directly iterating over the dictionary
for key in my_dict:
print(key)Both methods will output:
a
b
c
How to access values while iterating over a Python dictionary?
To access values while iterating over a dictionary, you can use the key to get the corresponding value:
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}for key in my_dict:
value = my_dict[key]
print(f"Key: {key}, Value: {value}")Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
What method is used to iterate over both keys and values in Python?
The
items()
method allows you to iterate over both keys and values in a dictionary. It returns a view object that displays a list of a dictionary’s key-value tuple pairs.# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
How to modify values during iteration in a Python dictionary?
To modify values during iteration, you can directly assign new values to the keys in the dictionary:
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}for key in my_dict:
my_dict[key] += 1print(my_dict)
Output:
{'a': 2, 'b': 3, 'c': 4}
Are there any Python modules that enhance dictionary iteration?
Yes, there are Python modules and functions that can enhance dictionary iteration. One such module is
collections
, which provides additional data structures likedefaultdict
andOrderedDict
. Additionally, tools from theitertools
module can be useful.Using
defaultdict
fromcollections
:from collections import defaultdict# Example defaultdict
my_dict = defaultdict(int, {'a': 1, 'b': 2, 'c': 3})for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")Using
OrderedDict
fromcollections
:from collections import OrderedDict# Example OrderedDict
my_dict = OrderedDict([('a', 1), ('b', 2), ('c', 3)])for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")Output:
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3Using
itertools
for advanced iteration:import itertools# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}# Iterating with itertools
for key, value in itertools.zip_longest(my_dict.keys(), my_dict.values()):
print(f"Key: {key}, Value: {value}")
Previous Article
Why is iterating over a dictionary slow in Python?
Next Article
Python - How to Iterate over nested dictionary ?