Iterating nested Python dictionaries

15,421

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.

Share:
15,421
Aidis
Author by

Aidis

Philosopher moving to sociology and looking for solutions provided by IT. Language: Python(beginner) and sql(starting soon). Interests-learning: regex, webscraping, databases, graph visualization Hobby: AI, game-theory and their application to strategy games (card games, starcraft, civilization and etc) www.aidisstuals.com

Updated on June 20, 2022

Comments

  • Aidis
    Aidis almost 2 years

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