'How to access the values of a nested dictionary structure
I have a nested dictionary structure and I want to iterate through it and print the values of each key within the nested key. For example:
animals = {
"Bear": {"food": "fish", "claws": "12"},
"Tiger": {"food": "meat", "claws": "8"},
"Elephant": {"food": "grass", "claws": "0"},
"Chicken": {"food": "feed", "claws": "talons"},
"Wolf": {"food": "rabbits", "claws": "6"}
}
target_animal = "Tiger"
tfood = ?
tclaws = ?
print("A tiger's food: "+ tfood)
print("A tiger's claws: "+ tclaws)
I have tried iterating through
if inner dictionary name == target_animal:
for i in kingdom.keys():
#print(i)
for j in kingdom[i]:
innerDict = (kingdom[i][j])
I do not know where to check for: if the inner dictionary name = "tiger", nor how to only access the values at the targeted inner dictionary.
The goal is to iterate through the 'animals' dictionary and if the key == the target_animal, print its inner dictionary values.
Solution 1:[1]
You just have to chain the brackets :
animals = {
"Bear": {"food": "fish", "claws": "12"},
"Tiger": {"food": "meat", "claws": "8"},
"Elephant": {"food": "grass", "claws": "0"},
"Chicken": {"food": "feed", "claws": "talons"},
"Wolf": {"food": "rabbits", "claws": "6"}
}
target_animal = "Tiger"
tfood = animals[target_animal]["food"]
tclaws = animals[target_animal]["claws"]
In the code above, you have animals[target_animal] which is equivalent to {"food": "meat", "claws": "8"}. This is itself a dictionary, so you can add the ["food"] and ["claws"] to access the value whitin.
Solution 2:[2]
animals = {
"Bear": {"food": "fish", "claws": "12"},
"Tiger": {"food": "meat", "claws": "8"},
"Elephant": {"food": "grass", "claws": "0"},
"Chicken": {"food": "feed", "claws": "talons"},
"Wolf": {"food": "rabbits", "claws": "6"}
}
# if you just wanna query for one animal, then
target_animal = "Tiger"
target_dict = animals['Tiger']
#dtype of target_dict again is a dict, so you can #again use indexing
tfood = target_dict['food']
tclaws = target_dict['claws']
print("A tiger's food: "+ tfood)
print("A tiger's claws: "+ tclaws)
If you want to iterate through everything
for animal, props in animals.items():
print(f"A {animal}'s food: {props['food']}")
print(f"A {animal}'s claws: {props['claws']}")
If you want to use iteration and still filter out only for tiger, then
for animal, props in animals.items():
if animal=='Tiger':
print(f"A {animal}'s food: {props['food']}")
print(f"A {animal}'s claws: {props['claws']}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Xiidref |
| Solution 2 | DharmanBot |
