迭代嵌套的Python字典

我试图从嵌套字典(从json加载)收集信息.我试图用for循环来做到这一点.我无法在字典中找到一个名为“players”的词典. “玩家”包含带有玩家姓名及其ID的字典.我想提取那本字典.您可以在下面找到我的代码和数据样本.

我能够通过第一级迭代到字典,但我无法过滤掉更深层次.

我一直在寻找其他类似的问题,但他们正在解决字典迭代的不同问题.我无法将它们用于我的目的.我正在考虑使用data.keys()[“players”]来提取我需要的信息,但我现在无法解决这个问题.

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

我的数据样本:

{
"[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": ""
    }
}
}
最佳答案
外部循环中的每个值本身都是一个字典:

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

在这里,您首先测试玩家键是否实际存在于嵌套字典中,然后如果是,则迭代所有键和玩家值的值,再次是字典.

转载注明原文:迭代嵌套的Python字典 - 代码日志