Understanding how to iterate through a Python dictionary is valuable. This technique allows you to read, manipulate, and output the contents of a dictionary. Looping in Python is easy. But beginners might find it a bit confusing, especially when using it with a more complex iterable such as a dictionary.

Here are some of the ways you can deal with a Python dictionary using loops.

Looping Through Keys and Values

A dictionary in Python contains key-value pairs. You can iterate through its keys using the keys() method:

        myDict = {"A" : 2, "B" : 5, "C" : 6}

for i in myDict.keys():
    print("Key"+" "+i)

<strong>Output:
Key A
Key B
Key C</strong>

The above code is slightly more verbose than you need, though. You can access the keys by calling them directly from myDict without using myDict.keys().

That's because a Python for loop picks the keys by default when it sees a dictionary. So you can write the above code like this instead:

        for key in myDict:
    print("Key"+ " " +key)

<strong>Output:
Key A
Key B
Key C</strong>

To access the values, use the corresponding values() method:

        myDict = {"A" : 2, "B" : 5, "C" : 6}

for i in myDict.values():
    print(i)

<strong>Output:
2
5
6</strong>

Similarly, you can access the values directly using their keys:

        for key in myDict:
    print(myDict[key])

<strong>Output:
2
5
6</strong>

While iterating through a dictionary, you can access its keys and values at the same time. You can do this in two ways.

The first method is to iterate through the dictionary and access the values using the dict[key] method. Then print each key-value pair within the loop:

        for key in myDict:
    print(key, "|", myDict[key])

<strong>Output:
A | 2
B | 5
C | 6</strong>

Alternatively, you can access the keys and values simultaneously using the items() method:

        for key, value in myDict.items():
    print(key, "|", value)

<strong>Output:
A | 2
B | 5
C | 6</strong>

Sometimes, you might want to output the result in reverse order. Here's how to do that using the sorted() function:

        myDict = {"A" : 2, "B" : 5, "C" : 6}

for key, value in sorted(myDict.items(), reverse=True):
    print(key, "|", value)

<strong>Output:
C | 6
B | 5
A | 2</strong>

Converting a Dictionary Into a List

Converting a dictionary into a list using iteration is as easy as transforming a list into a dictionary.

You can create a list containing an individual tuple for each key-value pair:

        myDict = {"A" : "MUO", "B" : "Google", "C" : "Python"}
myList = []
for key, value in myDict.items():
    myList.append((key, value))
print(myList)

<strong>Output: [('A', 'MUO'), ('B', 'Google'), ('C', 'Python')]</strong>

Or you can convert the dictionary into a nested list of key-value pairs:

        myDict = {"A" : "MUO", "B" : "Google", "C" : "Python"}
myList = []
for key, value in myDict.items():
    myList.append([key, value])
print(myList)

<strong>Output: [['A', 'MUO'], ['B', 'Google'], ['C', 'Python']]</strong>

And if you want to transform a dictionary into a stretched, or flattened, list:

        myDict = {"A" : "MUO", "B" : "Google", "C" : "Python"}
myList = []
for key, value in myDict.items():
    myList+= key, value
print(myList)

<strong>Output: ['A', 'MUO', 'B', 'Google', 'C', 'Python']</strong>

Adding Up the Values in a Dictionary

It's easy to sum all the values in a dictionary using a for loop:

        myDict = {"A":6, "B":7, "C":9}
g = 0 <em># initilize a variable to store the running total</em>
for i in myDict.values():
    g += i <em># add each value to the total</em>
print(g)

<strong>Output: 22</strong>

This is an iterative equivalent to using the sum() function which is an iterator itself. So you can add the values using sum() instead of looping as you did above:

        summedValues = sum(myDict.values())
print(summedValues)

<strong>Output: 22</strong>

Looping Through a Nested Python Dictionary

A nested dictionary might be a bit confusing to loop through at first. But it's as easy as iterating through a regular one.

The code below, for instance, outputs the content of each list in the dictionary:

        myDict = {"A" : [1, 2, 3], "B" : [4, 5, 6]}

for i in myDict.keys():
    print(myDict[i])

<strong>Output:
[1, 2, 3]
[4, 5, 6]</strong>

As it is in a regular dictionary, looping out the entire items outputs all key-value pairs in individual tuples:

        myDict = {"A" : [1, 2, 3], "B" : [4, 5, 6]}

for i in myDict.items():
    print(i)

<strong>Output:
('A', [1, 2, 3])
('B', [4, 5, 6])</strong>

Related:Python Dictionary: How You Can Use It To Write Better Code

You can also see specific values in a dictionary containing other dictionaries. But keep in mind that the values of a complex dictionary are the items of other dictionaries inside it. In essence, a complex dictionary contains parent and child keys.

Let's output the values in the complex dictionary below to see how this works:

        complexArray = {
    "Detail" : {
        "Name" : "Idowu",
        "Logs" : 20,
        "isAdmin" : True
    },
    "Activities" : {
    "Inputs" : 14,
    "Input Type" : "Video"
    }
}

for value in complexArray.values():
    print(value)

<strong>Output:
{'Name': 'Idowu', 'Logs': 20, 'isAdmin': True}
{'Inputs': 14, 'Input Type': 'Video'}</strong>

Using this insight, you can print specific values from the dictionary above.

To view the values of Detail, for instance:

        for value in complexArray["Detail"].values():
    print(value)

<strong>Output:
Idowu
20
True</strong>

Using a nested for loop, you can see all the values of all the child keys:

        for value in complexArray.values():
    for i in value.values(): <em># get the values of each key in the child dictionaries</em>
        print(i)

<strong>Output:
Idowu
20
True
14
Video</strong>

Regardless of their parent dictionary, the above iteration outputs all the child values from the nested dictionary.

Modifying Dictionary Items

Since a dictionary is mutable, you can modify its content as you like while iterating through it.

For instance, you can swap values for keys and insert the output in a new dictionary:

        myDict = {"A" : "MUO", "B" : "Google", "C" : "Python"}
swappedDict = {}
for key, value in myDict.items():
    swappedDict[value] = key
print(swappedDict)

<strong>Output: {'MUO': 'A', 'Google': 'B', 'Python': 'C'}</strong>

You can achieve the above using for loop in a dictionary comprehension as well:

        swappedDict = {value:key for key, value in myDict.items()}
print(swappedDict)

<strong>Output: {'MUO': 'A', 'Google': 'B', 'Python': 'C'}</strong>

You can also delete specific items from a dictionary while looping through it. This is a pretty handy way to remove duplicates.

The example code below removes duplicated items and inserts one of them back after iterating through the array:

        myDict = {"A" : "MUO", "B" : "Google", "C" : "Python", "C" : "Python"}
for key in list(myDict.keys()):
    if key == 'C':
        del myDict[key]
        myDict[key]="Python"
print(myDict)
<strong>Output: {'A': 'MUO', 'B': 'Google', 'C': 'Python'}</strong>

Play Around With Python Dictionaries

A Python dictionary is an essential tool for managing data in memory. So a basic understanding of the dictionary data structure, including how to iterate through it and get what you want, helps you in real-life scenarios.

And because you can customize what happens within a Python loop, it lets you manipulate your output. Nevertheless, iterating through a Python dictionary is easy once you understand the basic concepts of the Python loop.