简体   繁体   中英

Dict in dict, sort dictionary by nested key

I wanted to sort my dictionary in reverse order, order by nested dict 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"]},
}

to have this order:

'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']}

I've tried:

import operator

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

But no success.

You were close, but I'd suggest using a lambda function, which pulls the relevant value out of the dictionary in index one for each item;

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

Printing the output into a format where we can easily observe the order outputs;

for item in sorted_dict:
    print(item)

Which outputs;

('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']})

Instead of :

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

you should use:

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

It will sort the dictionary to your satisfaction!

Dictionaries are unordered in Python, and unless you use collections.OrderedDict , you will have to convert your structure to tuples and apply the sorted function

my_dict = mydict.items()

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

Output:

[('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'])])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM