![](/img/trans.png)
[英]Add same key but different values (coming from list) to a nested dictionary
[英]How to obtain multiple different values from the same key name in a nested dictionary?
我有一个嵌套的字典,它是最近玩过的游戏的匹配列表。 假设此字典(匹配列表)存储在变量m
。 内容如下:
{
"matches": [
{
"platformId": "NA1",
"gameId": 3000208798,
"champion": 7,
"queue": 420,
"season": 13,
"timestamp": 1552770736282,
"role": "SOLO",
"lane": "MID"
},
{
"platformId": "NA1",
"gameId": 3000221890,
"champion": 2,
"queue": 420,
"season": 13,
"timestamp": 1552768857241,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999711945,
"champion": 72,
"queue": 420,
"season": 13,
"timestamp": 1552722174457,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999696777,
"champion": 60,
"queue": 420,
"season": 13,
"timestamp": 1552720181393,
"role": "NONE",
"lane": "JUNGLE"
},
{
"platformId": "NA1",
"gameId": 2999691752,
"champion": 7,
"queue": 420,
"season": 13,
"timestamp": 1552718383760,
"role": "SOLO",
"lane": "MID"
}
],
"startIndex": 0,
"endIndex": 5,
"totalGames": 66
}
比赛列表包含5个比赛或游戏,我一直在尝试编写一个函数,该函数获取所有5个gameId
并以list
的形式返回它们。
我尝试了类似的东西:
def getGameIds():
gameIds = []
for "gameId" in m:
gameIds.append(m.get("gameId"))
return gameIds
以为我可以遍历每次出现的键"gameId"
,但是我没有任何运气。
尝试遍历添加到新列表的每个条目:
l = [i['gameId'] for i in data['matches']]
# [i.get('gameId') for i in data['matches']] also works
应产生包含以下内容的清单l
:
[3000208798, 3000221890, 2999711945, 2999696777, 2999691752]
您已经接近,但还没到那儿。 考虑一下您需要访问的每个元素:字典,然后是列表,然后是字典。 尝试以下方法:
def getGameIds():
gameIds = []
for subdict in m["matches"]:
gameIds.append(subdict.get("gameId"))
return gameIds
尝试这个:
l = [v for k,v in m.items() if k == "matches"]
glist = [i['gameId'] for d in l for i in d]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.