How to Iterate Through Dictionary in Python? – Definitive Guide

Python dictionary is a data structure that allows you to store values as a key-value pair.

After storing the values, you need to access them for various purposes. You can access the dictionary values by using its keys. If you want to perform an operation on entire values in the dictionary or if you do not know the key to fetch the item, you need to iterate through the entire dictionary.

You can iterate over the dictionary using the statement “for key, value in dict.items()”.

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. Then 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, then 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. Then 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.

This is how you can iterate through the dictionary values using for loop and the values() method provided by the python dictionaries.

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.

Then 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)

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.

Output

    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

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 Using Lambda

You may need to iterate through the dictionary to apply a function to each item in the dictionary. Applying a function means, to perform data manipulation on each item.

You can do this by using the lambda function and map().

Lambda function is to define a function that needs to be performed on each item in the dictionary.

map() is used to iterate the dictionary and apply the lambda function to each item in the dictionary.

In the below example,

  • lambda key: mydict[key]*10 – Lambda Function to multiply the value of each key by 10.
  • mydict.keys() – To iterate the keys of the dictionary.
  • Both the above is passed as parameter to the map. Which will apply the function to the each item in the dictionary.
  • The result of the map operation will be created as list using list() and assigned to the variable values.

Snippet

mydict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

values = list(map(lambda key: mydict[key]*10, mydict.keys()))

print(values)

You’ll see each value of the item in the dictionary will be multiplied by 10 and the result will be printed.

Output

    [10, 20, 30, 40]

This is how you can iterate over a dictionary using the lambda function.

Iterate Over Dictionary Using List Comprehension

List Comprehension provides a syntax to create a list-like object based on the values in the other list-like objects.

In this example, you’ll create a dictionary using the values of the other dictionary applying some conditions.

You can create a list only with the item value which is an even number in the dictionary.

  • Iterate the dictionary using for loop and items() method.
  • Apply the condition if val % 2 to check if the currently iterated value is an even number.
  • If its True, then the currently iterated item will be added to the resultant object. If False, it’ll not be added.

Snippet

mydict = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
}

even_val_dict = {key: val for key, val in mydict.items() if val % 2 == 0}

print(even_val_dict)

In the sample dictionary, the two items which are even numbers will be added in the output dictionary object and you’ll see the output as below.

Output

    {'two': 2, 'four': 4}

This is how you can iterate over a dictionary using list comprehension and apply a condition or perform data operation on the items in the dictionary.

Iterate Over Dictionary Of Lists

You can create a dictionary that has a list of values for each item.

In the below example, a dictionary is created with two items. One item with the odd numbers list and the other item with the even numbers list.

  • Iterate over the dictionary of lists using the list comprehension and the items() method.
  • During each iteration, use the for loop, which will iterate the values list and return it.
  • It’ll create a tuple with keys and values as shown below.

Snippet

numbers_list = {'odd': [1, 3, 5, 7, 8],
             'even': [2, 4, 6, 8, 10]
             }
all_numbers = [ (key, value) 
            for key, values in numbers_list.items() 
            for value in values ]

for num in all_numbers:
    print(num)

You can see each item in the list as shown below.

Output

    ('odd', 1)
    ('odd', 3)
    ('odd', 5)
    ('odd', 7)
    ('odd', 8)
    ('even', 2)
    ('even', 4)
    ('even', 6)
    ('even', 8)
    ('even', 10)

This is how you can iterate over a dictionary of lists.

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, then you can use for loop to iterate it.

Sort Using Dictionary Keys

In the below example,

  • sorted(mydict.keys()) – Sort the keys of the dictionary
  • for – 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 need to create a sorted set of keys.

Then you can 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 dictionary.
  • for val in sorted_keys: – iterates the sorted keys set.
  • sorted_dict[val] = mydict[val] – Access the dictionary and add the value to the sorted dictionary. Now this resultant dictionary will be having the sorted values. You can print it to check the results.

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 and items() method.
  • Check if the val is None using the if 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 iterate through the dictionary in python and you’ve also learned how to apply this method in different use-cases.

Also, you’ve used the lambda function along with map() and used list comprehension to loop through the items in the dictionary and apply a function to each item in the dictionary.

If you have any questions, comment below.

You May Also Like

Leave a Comment