我正在尝试从嵌套字典中收集信息(从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": ""
}
}
}
答案 0 :(得分:10)
外部循环中的每个value
本身都是一个字典:
for key, value in dct.iteritems():
if 'players' in value:
for name, player in value['players'].iteritems():
print name, player
在这里,首先测试嵌套字典中是否存在players
键,如果是,则迭代players
值的所有键和值,再次是字典。< / p>
答案 1 :(得分:0)
for team in myData:
for player,id in myData[team]['players'].iteritems():
print "player %s has ID '%s'" %(player, id)