首页 > 解决方案 > 对字典/json文件中的值进行排序

问题描述

我有这个 discord.py 命令,可以从 json 制作排行榜

在此处输入图像描述

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/member ids)

如何使代码更短更清晰?

感谢您提前提供帮助,因为我真的不知道解决方案

标签: pythonjsondiscord.py

解决方案


在查找(排序)字典中的前十个项目时,这种方法比反复浏览字典并在那里做不同的事情要容易得多。

还有更好的代码,比如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)

推荐阅读