Iterate Python Nested Dictionaries

I am trying to collect information from nested dictionaries (downloaded from json). I am trying to do this with a loop. I could not get the dictionary in the dictionary called "players". "players" contain a dictionary with the names of players and their identifiers. I would like to extract this dictionary. You can find my code and sample data below.

I managed to sort out the first level into a dictionary, but I canโ€™t filter out the deeper levels.

I looked at other similar questions, but they solved different problems of dictionary iteration. I could not use them for my own purposes. I was thinking about retrieving the information I need using data.keys () ["players"], but I can't handle it at the moment.

for key, value in dct.iteritems(): if value == "players": for key, value in dct.iteritems(): print key, value 

Sample of my data:

 { "[CA1]": { "team_tag": "[CA1]", "team_name": "CzechAir", "team_captain": "MatejCzE", "players": { "PeatCZ": "", "MartyJameson": "", "MidnightMaximus": "", "vlak_in": "", "DareD3v1l": "", "Hugozhor78": "" } }, "[GWDYC]": { "team_tag": "[GWDYC]", "team_name": "Guys Who Dated Your Cousin", "team_captain": "Teky1792", "players": { "wondy22": "", "dzavo1221": "", "Oremuss": "", "Straker741": "", "Vasek9266": "" } } } 
+7
json python dictionary loops iteration
source share
2 answers

Each value in the outer loop is itself a dictionary:

 for key, value in dct.iteritems(): if 'players' in value: for name, player in value['players'].iteritems(): print name, player 

Here you first check whether the players key is actually present in the embedded dictionary, and then, if it exists, iterates over all the keys and values โ€‹โ€‹of the players value, again the dictionary.

+10
source share
 for team in myData: for player,id in myData[team]['players'].iteritems(): print "player %s has ID '%s'" %(player, id) 
0
source share

All Articles