我想按值对嵌套字典排序,按另一个值对余数进行排序,再按另一个值对余数进行排序。我有三个条件。我要为三个中的两个分配reverse = True,但是对于第三个条件,我想要分配reverse = False。如何使用reversed和lambda? 这是一段代码:
Map
k [1] [“ W”]和k [1] [“ PKT”]必须相反,而k [1]不能相反。
答案 0 :(得分: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)