Friday, September 17, 2021

How to Loop Through a Dictionary in Python - MakeUseOf - Dictionary

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)
Output:
Key A
Key B
Key C

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)
Output:
Key A
Key B
Key C

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

myDict = {"A" : 2, "B" : 5, "C" : 6}
for i in myDict.values():
print(i)
Output:
2
5
6

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

for key in myDict:
print(myDict[key])
Output:
2
5
6

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])
Output:
A | 2
B | 5
C | 6

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

for key, value in myDict.items():
print(key, "|", value)
Output:
A | 2
B | 5
C | 6

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)
Output:
C | 6
B | 5
A | 2

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)
Output: [('A', 'MUO'), ('B', 'Google'), ('C', 'Python')]

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)
Output: [['A', 'MUO'], ['B', 'Google'], ['C', 'Python']]

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)
Output: ['A', 'MUO', 'B', 'Google', 'C', 'Python']

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 # initilize a variable to store the running total
for i in myDict.values():
g += i # add each value to the total
print(g)
Output: 22

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)
Output: 22

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])
Output:
[1, 2, 3]
[4, 5, 6]

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)
Output:
('A', [1, 2, 3])
('B', [4, 5, 6])

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)
Output:
{'Name': 'Idowu', 'Logs': 20, 'isAdmin': True}
{'Inputs': 14, 'Input Type': 'Video'}

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)
Output:
Idowu
20
True

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(): # get the values of each key in the child dictionaries
print(i)
Output:
Idowu
20
True
14
Video

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)
Output: {'MUO': 'A', 'Google': 'B', 'Python': 'C'}

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)
Output: {'MUO': 'A', 'Google': 'B', 'Python': 'C'}

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)
Output: {'A': 'MUO', 'B': 'Google', 'C': 'Python'}

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.

HHow to Use For Loop in Python - Featured
How to Use For Loops in Python

For Loops are an essential programming skill. Learn how to use them in Python here.

About The Author

Adblock test (Why?)

No comments:

Post a Comment