在python中,我想根据字典值的字典对字典进行排序

时间:2018-09-09 01:49:27

标签: python dictionary

在python中,我有一个字典,例如

my_dict = {A:{mark1:15, mark2:12, mark3:20}, B:{mark1:10, mark2:90, 
mark3:14},C:{mark1:11, mark2:19, mark3:25}}

我想打印基于每个mark3排序的字典,例如我想以这种格式打印(我只是不知道如何基于mark3排序?)

C : {mark1:11, mark2:19, mark3:25}
A : {mark1:15, mark2:12, mark3:20}
B : {mark1:10, mark2:90, mark3:14}

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用自定义键进行排序:

print(dict(sorted(my_dict.items(), key=lambda x: x[1]['mark3'], reverse=True)))

这将输出(在Python 3.6+中):

{'C': {'mark1': '11', 'mark2': '19', 'mark3': '25'}, 'A': {'mark1': '15', 'mark2': '12', 'mark3': '20'}, 'B': {'mark1': '10', 'mark2': '90', 'mark3': '14'}}

Python 3.6字典之前的命令是无序的,因此应改用collections.OrderedDict

from collections import OrderedDict
my_dict = OrderedDict([('A', {'mark1': '15', 'mark2': '12', 'mark3': '20'}), ('B', {'mark1': '10', 'mark2': '90', 'mark3': '14'}), ('C', {'mark1': '11', 'mark2': '19', 'mark3': '25'})])
print(OrderedDict(sorted(my_dict.items(), key=lambda x: x[1]['mark3'], reverse=True)))

如果要将mark2用作辅助键,则可以将其设为元组:

print(dict(sorted(my_dict.items(), key=lambda x: (x[1]['mark3'], x[1]['mark2']), reverse=True)))