简体   繁体   中英

sort only dictionary values that are lists within a list

I have this type of dict;

dict2 = {'value1': [ 2, ['get1', 3], ['post3', 4] ], 'value2' : [1, ['get1', 2], ['post2', 5] ], 'value3' : [7, ['get17', 6], ['post2', 2], ['post3', 3] ] }

I know how to order this based on the first value in the list (7, 2, 1). However once I've sorted it by the first value object, I want to sort the lists only based on the second value in each list.

For example like this;

'value3' : [7, ['get17', 6], ['post3', 3], ['post2', 2] ],
'value1': [ 2, ['post3', 4], ['get1', 3] ],
'value2' : [1,  ['post2', 5], ['get1', 2] ]

I've been looking into things like itemgetter but can't figure it out. Is this possible with python?

edit:

This is how I'm sorting the first value object, to print;

for key, value in sorted(dict2.iteritems(), key=lambda (k,v): (v,k), reverse=True):
    print key, value

To put into variable;

sort1 = sorted(dict2.items(), key=operator.itemgetter(1, 1), reverse=True)

You should consider getting the items as a list or tuple and them sorting them with a function or lambda expression like so:

items = dict2.items()
items.sort(key=lambda x:x[1][0])

Since you already know how to sort based on the first value in the dict, let's focus on sorting the inner sequences. The important step is to use slicing to trim-off the initial value so you can sort the remaining pairs:

>>> for key, seq in dict2.items():
        dict2[key] = seq[:1] + sorted(seq[1:], key=itemgetter(1), reverse=True)


>>> pprint(dict2)
{'value1': [2, ['post3', 4], ['get1', 3]],
 'value2': [1, ['post2', 5], ['get1', 2]],
 'value3': [7, ['get17', 6], ['post3', 3], ['post2', 2]]}

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