首页 > 解决方案 > 按值对 2d dict 排序

问题描述

我有一个像这样的二维字典:
{'John' : {'a' : 9, 'b' : 2, 'c': 5}, 'Smith' : {'d' : 1, 'r' : 3, 'f': 4}}


我想打印/保存它们,排序,如下所示:
John a 9
John c 5
Smith f 4
Smith r 3
John b 2
Smith d 1

这样它们就按其内在价值进行排序。两个键都是事先不知道的。

有没有办法做到这一点?谢谢!

标签: python-3.xdictionary

解决方案


一种可能性是扩展字典,然后执行排序:

two_dimensional_dictionary = {'John' : {'a' : 9, 'b' : 2, 'c': 5}, 'Smith' : {'d' : 1, 'r' : 3, 'f': 4}}

values = [(first_key, second_key, value) 
          for first_key, values in two_dimensional_dictionary.items() 
          for second_key, value in values.items()]
print(list(sorted(values, key=lambda x:x[-1], reverse=True)))

输出:

[('John', 'a', 9), ('John', 'c', 5), ('Smith', 'f', 4), ('Smith', 'r', 3), ('John', 'b', 2), ('Smith', 'd', 1)]
``

推荐阅读