Python dictionary is a data structure that allows you to store values as a key-value pair.
You can iterate through the dictionary in Python using the dict.items()
method.
In this tutorial, you’ll learn how to iterate through the dictionary in Python.
If you’re in Hurry
You can use the below code snippet to iterate over the dictionary items.
You’ll get both the key and value of each item during each iteration.
Snippet
for key, value in mydict.items():
print(key ,value)
You’ll see all the items in the dictionary are printed as below.
Output
one 1
two 2
three 3
four 4
If you’re iterating through the dictionary just to check if a specific key exists in the dictionary, check the guide How to Check If Key Exists in Dictionary.
If You Want to Understand Details, Read on…
In this tutorial, you’ll learn the different methods available to loop through the dictionary keys, values, or the items themselves.
Sample Dictionary
mydict = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
}
The above dictionary will be used for the demonstration purpose of the complete tutorial. However, tweaks will be made as required to match the demonstration of different use cases.
In most cases, you’ll iterate through the dictionary using for
loop and the iterable methods provided by the dictionary to iterate through it.
Using Keys() Method
You can use the keys()
method provided by the dictionary to iterate through the keys of the dictionary.
- It returns an iterable of the keys available in the dictionary.
- Using for loop, you can iterate through the keys as shown below.
Snippet
for key in mydict.keys():
print(key)
Output
one
two
three
four
Snippet 2
If you want to access the value of the key, you can use the get()
method to get the value of the specific key during each iteration, as shown below.
for key in mydict.keys():
print(mydict.get(key))
Output
1
2
3
4
This is how you can iterate through the dictionary keys using for
loop and the keys()
method provided by the python dictionaries.
Using Values() Method
You can use the values()
method provided by the dictionary to iterate through the values of the dictionary items.
- It returns an
iterable
of the values of each item available in the dictionary. - Using
for
loop, you can iterate through the values as shown below.
Snippet
for value in mydict.values():
print(value)
You’ll see the value of each item in the dictionary printed as below.
Output
1
2
3
4
Using this method will not give access to the dictionary keys()
which is not necessary in most cases.
This makes this method the fastest method to iterate through the dictionary.
Using Items() method
You can iterate through the dictionary items using the items()
method provided by the python dictionary.
items()
method returns a tuple of key-value pair during each iteration.- using for loop, you can iterate through the key-value pair and access both the keys and values in the same iteration as shown below.
Snippet
for key, value in mydict.items():
print(key ,value)
Output
You’ll see the below output. Keys and values will be printed for each iteration and no additional access to the dictionary is necessary to fetch the value of the key.
one 1
two 2
three 3
four 4
This is how you can access the items of the dictionary using for
loop and the items() method provided by the dictionaries.
Iterating Through Keys Directly Using For Loop
You can access the items in the dictionary using the for
loop directly.
It iterates through the keys of the dictionary, and this is an alternative to using the keys()
method.
Snippet
for key in mydict:
print(key , mydict.get(key))
When using the dictionary directly, it returns only the keys during the iteration.
You can access the value of each key by using the get()
method.
Output
one 1
two 2
three 3
four 4
This is how you can loop through a dictionary using the for
loop directly without using the methods provided by python dictionaries.
Iterate Over dictionary With Index
You can also iterate through the dictionary using the index of the items.
This is similar to iterating the dictionary without using the methods such as keys()
, values()
or items()
.
Snippet
for i in mydict:
print(i, mydict[i])
You’ll see all the items printed as shown below.
Output
one 1
two 2
three 3
four 4
Iterate Over Dictionary In Alphabetical Order
Dictionaries typically don’t maintain any order. This means the order of the items during the iteration is not guaranteed.
To iterate a dictionary using the specific order, you can use the sorted()
function in python. It’ll sort the object first and you can use for
loop to iterate it.
Sort Using Dictionary Keys
In the below example,
sorted(mydict.keys())
– Sort the keys of the dictionaryfor
– iterates the keys returned by the sorted method.
Snippet
mydict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
for key in sorted(mydict.keys()):
print(key, mydict[key])
You’ll see the below output as the keys will be sorted alphabetically.
Output
four 4
one 1
three 3
two 2
Sort Using Dictionary Item Values
To sort the dictionary based on its values,
- first, you create a sorted set of keys.
- Iterate the sorted keys set and access the dictionary using the key during each iteration.
In the below example,
sorted_keys = sorted(mydict, key=mydict.get)
– Creates a set of sorted keys from the dictionaryfor val in sorted_keys:
– iterates the sorted keys setsorted_dict[val] = mydict[val]
– Access the dictionary and add the value to the sorted dictionary.
Now, this resultant dictionary will have the sorted values.
Snippet
mydict = {
"four": 4,
"two": 2,
"three": 3,
"one": 1
}
sorted_dict = {}
sorted_keys = sorted(mydict, key=mydict.get)
for val in sorted_keys:
sorted_dict[val] = mydict[val]
print(sorted_dict)
Output
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
This is how you can sort dictionaries based on the values.
Iterate Over Dictionary And Update Values
Dictionary is an object which contains a list of values.
Apart from accessing the items in the dictionary, you may also need to update the values of the item in the dictionary.
In this section, you’ll learn how to iterate over dictionary and update values based on some condition.
- Iterate the dictionary using the
for
loop anditems()
method. - Check if the val is
None
using theif
statement. - If
None
, assign the empty value using''
.
In the below example, the dictionary has an item which has one item with a value None
.
Snippet
mydict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": None
}
for key, val in mydict.items():
if val is None:
mydict[key] = ''
print(mydict)
Once the script is executed, you’ll see the value ''
value updated for the key five
as shown below.
Output
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': ''}
This is how you can loop through the dictionary and update values.
Conclusion
To summarize, you’ve learned the different methods to loop through the dictionary in python and you’ve also learned how to apply this method in different use-cases.
If you have any questions, comment below.