【问题标题】:Sort a dictionary depending of some value [closed]根据某些值对字典进行排序[关闭]
【发布时间】:2021-09-24 22:12:40
【问题描述】:
"users": {
    "673336994218377285": {"votes": 5},
    "541388453708038165": {"votes": 1},
    "845444326065700865": {"votes": 9}
}

如何根据嵌套字典的“votes”键对字典进行排序?字典应该是这样的:

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

【问题讨论】:

标签: python sorting dictionary


【解决方案1】:

Python 中的字典(自 3.6 起)按其插入顺序排序,因此您必须创建一个新字典,其中的元素按其排序顺序插入:

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

dict(sorted(users.items(), key=lambda x: x[1]['votes'], reverse=True))

key=lambda x: x[1]['votes'] 使它根据每个项目的值的“投票”字段对每个元素进行排序。

如果您使用的是旧版本的 Python,则不会对字典进行排序,因此您必须对 collections.OrderedDict 使用相同的方法,而不是 dict

【讨论】:

  • 1 班轮解决方案的简短说明。我们排序的集合是字典items。它是一个有 2 个插槽的元组:0 -> 键,1 -> 值。这就是为什么lambda 使用x[1]['votes']
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2011-12-11
相关资源
最近更新 更多