Bootstrap FreeKB - Python (Scripting) - Loop over a dictionary
Python (Scripting) - Loop over a dictionary

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter e9dea0 in the box below so that we can be sure you are a human.