dict中的dict,通过嵌套键排序字典

时间:2017-07-21 13:39:58

标签: python sorting dictionary nested key

我想按相反顺序对字典进行排序,按嵌套字典键0:

排序
mydict = {
          'key1': {0: 3, 1: ["doc1.txt", "doc2.txt"], 2: ["text1", "text2"]},
          'key2': {0: 8, 1: ["doc6.txt", "doc7.txt"], 2: ["text3", "text4"]},
          'key3': {0: 1, 1: ["doc8.txt", "doc9.txt"], 2: ["text7", "text8"]},
}

订购此订单:

'key3': {0: 1, 1: ['doc8.txt', 'doc9.txt'], 2: ['text7', 'text8']}
'key1': {0: 3, 1: ['doc1.txt', 'doc2.txt'], 2: ['text1', 'text2']}
'key2': {0: 8, 1: ['doc6.txt', 'doc7.txt'], 2: ['text3', 'text4']}

我试过了:

import operator

sorted_dict = sorted(mydict.items(), key=operator.itemgetter(0), reverse=True)

但没有成功。

3 个答案:

答案 0 :(得分:0)

你很接近,但我建议使用lambda函数,它会将相关值从每个项目的索引1中的字典中提取出来;

sorted_dict = sorted(mydict.items(), key=lambda x: x[1][0])

将输出打印成我们可以轻松观察订单输出的格式;

for item in sorted_dict:
    print(item)

哪些输出;

('key3', {0: 1, 1: ['doc8.txt', 'doc9.txt'], 2: ['text7', 'text8']})
('key1', {0: 3, 1: ['doc1.txt', 'doc2.txt'], 2: ['text1', 'text2']})
('key2', {0: 8, 1: ['doc6.txt', 'doc7.txt'], 2: ['text3', 'text4']})

答案 1 :(得分:0)

而不是:

sorted_dict = sorted(mydict.items(), key=operator.itemgetter(0), reverse=True)

你应该使用:

sorted_dict = sorted(mydict.items(), key=operator.itemgetter(1))

它会对字典进行排序,让您满意!

答案 2 :(得分:0)

字典在Python中是无序的,除非您使用collections.OrderedDict,否则您必须将结构转换为元组并应用sorted函数

my_dict = mydict.items()

final = sorted([(a, b.items()) for a, b in my_dict], key=lambda x:x[1][0][1])

输出:

[('key3', [(0, 1), (1, ['doc8.txt', 'doc9.txt']), (2, ['text7', 'text8'])]), 
 ('key1', [(0, 3), (1, ['doc1.txt', 'doc2.txt']), (2, ['text1', 'text2'])]), 
 ('key2', [(0, 8), (1, ['doc6.txt', 'doc7.txt']), (2, ['text3', 'text4'])])]