Python (Scripting) - Loop over a dictionary

by
Jeremy Canfield |
Updated: August 25 2024
| Python (Scripting) articles
Let's say you have an dictionary (key:value pairs) of food. Here is how you can loop through the dictionary.
#!/usr/bin/python3
dictionary = {
"fruit":"apple",
"veggy":"tomato",
"grain":"rice"
}
for key in dictionary:
print(f"{key} = {dictionary[key]}")
The following should be returned.
fruit = apple
grain = rice
veggy = tomato
And let's say you have a nested dictionary.
#!/usr/bin/python3
dictionary = {
"food":{
"fruit":"apple",
"veggy":"tomato",
"grain":"rice"
}
}
for key in dictionary:
print(f"key = {key}")
for item in dictionary[key]:
print(f"{item} = {dictionary[key][item]}")
Or like this.
#!/usr/bin/python3
dictionary = {
"food":{
"fruit":"apple",
"veggy":"tomato",
"grain":"rice"
}
}
for item in dictionary['food']:
print(f"{item} = {dictionary['food'][item]}")
The following should be returned.
key = food
fruit = apple
grain = rice
veggy = tomato
Let's say you have a dictionary that contains two or more nested list. Here is an example of how you could loop through the dictionary.
#!/usr/bin/python3
dictionary = {
"foo": [
{
"bar": [
{ "hello": "world" }
]
}
]
}
for index, key in enumerate(dictionary):
print(f"index = {index}")
print(f"key = {key}")
for sub_key in dictionary['foo'][index]:
print(f"sub_key = {sub_key}")
for sub_dict in dictionary['foo'][index][sub_key]:
print(f"sub_dict = {sub_dict}")
print(f"sub_dict['hello'] = {sub_dict['hello']}")
Running this script should return the following.
index = 0
key = foo
sub_key = bar
sub_dict = {'hello': 'world'}
sub_dict['hello'] = world
Did you find this article helpful?
If so, consider buying me a coffee over at