python - 对字典/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)
如何使代码更短更清晰?
感谢您提前提供帮助,因为我真的不知道解决方案
解决方案
在查找(排序)字典中的前十个项目时,这种方法比反复浏览字典并在那里做不同的事情要容易得多。
还有更好的代码,比如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)
推荐阅读
- visual-studio-code - 如何注入/跟踪编辑器/文档元数据?
- react-native - 在 React Native 中使用物理单位(厘米、英寸)调整大小
- javascript - 如何使用 JavaScript 正确查询选择器结果?
- python - NameError:名称'app'未在Flask中定义
- java - mvn clean quarkus:dev 在 intellij IDEA 的终端上不起作用
- c# - C#中整数的逻辑与运算
- arrays - 获取数组中重复值的总和,但前提是它们并排
- python-3.x - For-loop 在字符串列表中搜索子字符串列表时跳过一个术语
- python - tesseract:如何使用用户词 python
- python - 无法正确安装 python 库