Aidis
Aidis

Reputation: 1280

Iterating nested Python dictionaries

I am trying to collect info from nested dictionaries (loaded from json). I am trying to do that with for loop. I was unable to get a dictionary inside dictionary that is named "players". "players" contains dictionary with player names and their ids. I would like to extract that dictionary. You can find my code and sample of data below.

I was able to iterate through first level to dictionary, but I cannot filter out deeper levels.

I have been looking through other similar questions, but they were tackling different issues of dictionary iteration. I was not able to use them for my purposes. I was thinking about extracting the info that I need by using data.keys()["players"], but I cant handle this at the moment.

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

A 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": ""
    }
}
}

Upvotes: 7

Views: 15979

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 113905

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121196

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 test first if the players key is actually present in the nested dictionary, then if it is, iterate over all the keys and values of the players value, again a dictionary.

Upvotes: 10

Related Questions