对字典/json文件中的值进行排序

2024-10-01 00:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个discord.py命令,它通过json创建排行榜

enter image description here

cogs/coins.json(字典)如下所示:

{
  "781524858026590218": {
        "name": "kvbot test platform",
        "total_coins": 129,
        "data": {
            "564050979079585803": {
                "name": "Bluesheep33",
                "coins": 127
            },
            "528647474596937733": {
                "name": "ACAT_",
                "coins": 2
            }
}

(json文件中带数字的绿色字符串是discord guild/成员ID)

如何使代码更短更清晰

谢谢你提前帮忙,因为我真的不知道解决办法


Tags: namepytest命令jsondata字典total
1条回答
网友
1楼 · 发布于 2024-10-01 00:19:28

当涉及到在一个dict中查找(排序)前十项时,这种方法要比反复检查dict并在那里做不同的事情容易得多

还有一些更好的代码,比如用于安全访问的Dict.get

基于JSON数据示例

with open('cogs/coins.json', 'r') as f:
    coins_data = json.load(f)

# Get is safefy access to dict
# Dict.items() returns pairs of (Key, Val)
members_coins = list(coins_data.get(str(ctx.guild.id), None)['data'].items())

if members_coins is None:  # If data not found
    await ctx.send('Not data')
    return

# Sort list by Val part of pair, and `coins` key, reverse for descending
members_coins.sort(key=lambda x: x[1]['coins'], reverse=True)

output = ''
# list[:10] for first 10 items (if list is smaller, thats okay, python don't mind)
for member_id, vals in members_coins[:10]:
    output += f'{vals["name"]}: {vals["coins"]}'
    # output += f'<@{member_id}>: {vals["coins"]}'  # If you want "mention" display of user

await ctx.send(output)

相关问题 更多 >