从字典中的多个嵌套列表中提取所有值

问题描述 投票:0回答:1

看看这本词典:

{
    "0": {
        "server": 681262466650734596,
        "channel": 693639674841006101,
        "balance": 1000,
        "bal2": 30000,
        "regd": [
            {
                "user": 624748908479905812,
                "exp": 2015.0,
                "rank": 2,
                "points": 125.69999999999996,
                "msgs": 9999,
                "tokens": 10000
            },
            {
                "user": 1096531392369807492,
                "exp": 501.0,
                "rank": 1,
                "points": 1.4000000000000004,
                "msgs": 1,
                "tokens": 10000
            },
            {
                "user": 603657446233210908,
                "exp": 600,
                "rank": 2,
                "points": 169,
                "msgs": 0,
                "tokens": 12000
            },
            {
                "user": 248793436293955584,
                "exp": 630,
                "rank": 2,
                "points": 169,
                "msgs": 0,
                "tokens": 12000
            },
            {
                "user": 217098431393431553,
                "exp": 555,
                "rank": 2,
                "points": 169,
                "msgs": 0,
                "tokens": 12000
            }
        ]
    }
}

我正在尝试编写一个函数(带有参数:服务器编号),该函数将迭代该字典,找到具有匹配服务器编号的字典,然后迭代“regd”键/值并返回所有“exp”值。 例如,

e = 'exp'
search_dictionary(serverNum, e)

search_dictionary 函数不完整,不知道如何继续,但所需的输出是列表中的每个 exp 值,例如:[2015.0, 501.0, 600, 630, 555]

我目前有此功能,但不起作用:

def PBX(self, User: int, Server: int):
        dop = self.ReadLevel()
        for key, value_key in dop.items():
            if value_key['server'] == Server:
                nd = value_key['regd']
                for key, value in nd.items():
                    if 'exp' in key:
                        res = []
                        res.append(value['exp'])
                        print(res)
                    return

有人可以帮我吗?我之前也做过类似的事情,昨天我决定修改字典样式,仍在研究如何使用新样式提取数据

python discord.py review
1个回答
0
投票

你可以这样做:


def get_exps(dct, server_num):
    out = []

    for d in dct.values():
        if d["server"] == server_num:
            for i in d["regd"]:
                out.append(i["exp"])
            break

    return out

dct = ... # your dictionary from the question

print(get_exps(dct, 681262466650734596))

打印:

[2015.0, 501.0, 600, 630, 555]

如果未找到服务器号码,则返回空列表。

© www.soinside.com 2019 - 2024. All rights reserved.