This question already has an answer here:
- Loop through all nested dictionary values? 11 answers
I have the below code which currently just prints the values of the initial dictionary. However I would like to iterate through every key of the nested dictionary to initially just print the names. Please see my code below:
Liverpool = {
'Keepers':{'Loris Karius':1,'Simon Mignolet':2,'Alex Manninger':3},
'Defenders':{'Nathaniel Clyne':3,'Dejan Lovren':4,'Joel Matip':5,'Alberto Moreno':6,'Ragnar Klavan':7,'Joe Gomez':8,'Mamadou Sakho':9}
}
for k,v in Liverpool.items():
if k =='Defenders':
print(v)
Here is code that would print all team members:
So you just iterate every inner dictionary one by one and print values.
In other answers, you were pointed to how to solve your task for given dicts, with maximum depth level equaling to two. Here is the program that will alows you to loop through key-value pair of a dict with unlimited number of nesting levels (more generic approach):
Prints
That is relevant if you are interested only in key-value pair on deepest level (when value is not dict). If you are also interested in key-value pair where value is dict, make a small edit:
Prints
Yields: