如何从嵌套字典中的相同键名获取多个不同的值?

时间:2019-03-20 00:18:11

标签: python 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"的每次出现,但是我没有任何运气。

3 个答案:

答案 0 :(得分:3)

尝试遍历添加到新列表的每个条目:

l = [i['gameId'] for i in data['matches']]
# [i.get('gameId') for i in data['matches']] also works

应产生列表l,其中包含:

[3000208798, 3000221890, 2999711945, 2999696777, 2999691752]

答案 1 :(得分:3)

您正在接近,但还没到那儿。考虑一下您需要访问的每个元素:字典,然后是列表,然后是字典。尝试以下方法:

def getGameIds():
    gameIds = []
    for subdict in m["matches"]:
        gameIds.append(subdict.get("gameId"))
    return gameIds

答案 2 :(得分:0)

尝试一下:

SELECT SUM(a.points) AS mysum FROM __CLASS__ a WHERE a.user = :user GROUP BY a.user