【问题标题】:How to sort a nested dictionary?如何对嵌套字典进行排序?
【发布时间】:2020-04-29 13:49:40
【问题描述】:

我想按值对嵌套字典进行排序,按另一个值对余数进行排序,再按另一个值对余数进行排序。我有三个标准。我想给他们三个中的两个分配reverse=True,但是对于第三个条件我想分配reverse=False。如何使用 reversed 和 lambda 来做到这一点? 下面是一段代码:

result = sorted(dict_punkty.items(), key=lambda k: (k[1]["W"], k[1]["PKT"], k[1]), reverse=True)

k[1]["W"] 和 k[1]["PKT"] 必须倒序,k[1] 不能倒序。

【问题讨论】:

  • 如果值是数字,您可以按- value 为您想要的倒序排序。但我们不知道,所以你应该提供一个最小的样本字典。
  • {'Jan': {'W': 1, 'PKT': 25}, 'Artur': {'W': 1, 'PKT': 20}, 'Karol': { “W”:0,“PKT”:10}}
  • @kasiabadio: k[1] 是一个 dict,但在 Python 3 中的 dicts 上的顺序比较是 not allowed,即使在 Python 2 中,dicts 的顺序也是 consistent but not defined。那么(我假设您使用的是 Python 2)k[1] 被“不按相反顺序”排序意味着什么?由于未定义顺序,这与反向顺序有何不同?您的意思是将k[0] 改为第三项吗?

标签: python sorting dictionary lambda


【解决方案1】:

我找不到更短的东西,所以我建议以下解决方案:

dict_punkty={'Jan': {'W': 1, 'PKT': 25}, 'Artur': {'W': 1, 'PKT': 20}, 'Karol': {'W': 0, 'PKT': 10}}

# Put key names in a list sorted in reverse order
names = sorted(dict_punkty.keys(), reverse=True)

# Put names and their order in a temporary dictionary
names = {name: i for i, name in enumerate(names)}

# Put the data in a list of tuples replacing key names with order numbers
result = [(names[k[0]], k[1]) for k in dict_punkty.items()]

# Sort the list of tuples
result = sorted(result, key=lambda k: (k[1]["W"], k[1]["PKT"], k[0]), reverse=True)

# Reverse names/orders as keys/values in the temporary dictionary
names = {i: name  for name, i in names.items()}

# Get the final result by replacing the order numbers with key names
result = [(names[k[0]], k[1]) for k in result]

print(result)

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2015-03-31
    • 1970-01-01
    • 2016-01-17
    • 2020-11-11
    • 1970-01-01
    • 2021-05-31
    • 2014-05-01
    • 1970-01-01
    相关资源
    最近更新 更多