Python (Scripting) - Loop over a dictionary
by
Jeremy Canfield |
Updated: November 06 2023
| 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
Did you find this article helpful?
If so, consider buying me a coffee over at