Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": ""
    }
}
}
like image 546
Aidis Avatar asked Jan 03 '14 14:01

Aidis


People also ask

How do you iterate over a nested dictionary in Python?

just write d. items() , it will work, by default on iterating the name of dict returns only the keys.

How do you iterate over nested dictionaries?

Iterate over all values of a nested dictionary in python For a normal dictionary, we can just call the items() function of dictionary to get an iterable sequence of all key-value pairs.

How do I iterate a list of dictionaries in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.


1 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 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.

like image 126
Martijn Pieters Avatar answered Oct 26 '22 04:10

Martijn Pieters