You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据嵌套字典的votes键值对用户字典进行降序排序

按嵌套votes字段降序排序字典的实现方法

适用前提

Python 3.7及以上版本中,内置字典默认保留插入顺序,可直接使用以下方案。如果使用3.7以下版本,需配合collections.OrderedDict使用。

实现代码

1. 定义原始数据

data = {
    "users": {
        "673336994218377285": {"votes": 5},
        "541388453708038165": {"votes": 1},
        "845444326065700865": {"votes": 9}
    }
}

2. 核心排序逻辑

调用sorted方法对users字典的键值对进行排序,通过key参数指定排序依据为嵌套的votes值,设置reverse=True实现降序:

# 排序后生成新的有序字典
sorted_users = dict(sorted(
    data["users"].items(),
    key=lambda item: item[1]["votes"],
    reverse=True
))

# 替换原数据中的users字段
data["users"] = sorted_users

3. Python 3.7以下版本兼容方案

引入OrderedDict存储排序结果,保证顺序不会丢失:

from collections import OrderedDict

sorted_users = OrderedDict(sorted(
    data["users"].items(),
    key=lambda item: item[1]["votes"],
    reverse=True
))
data["users"] = sorted_users

最终输出效果

执行完成后,data的结构就和目标结构完全一致:

"users": {
    "845444326065700865": {"votes": 9},
    "673336994218377285": {"votes": 5},
    "541388453708038165": {"votes": 1}
}

内容的提问来源于stack exchange,提问作者FoxGames01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:57:02