简体   繁体   中英

Python-3.x: Reverse sort a dictionary of lists based on number of items in each list

I want to reverse sort a dictionary of lists based on the number of items in each list , and keep the keys for further processing. Ie I do not want a list returned.

Example:

test = {346: [235, 238], 347: [129, 277], 348: [115, 191, 226], 349: [194, 328], 351: [150, 70, 118], 352: [123, 334], 353: [161, 196]}

After sorting the dict the desired output should be something like:

test = {348: [115, 191, 226], 351: [150, 70, 118], 346: [235, 238], 347: [129, 277], 349: [194, 328], 352: [123, 334], 353: [161, 196]}

What I have come up with so far is:

def get_length(element):
    return len(element)


test = {346: [235, 238], 347: [129, 277], 348: [115, 191, 226], 349: [194, 328], 351: [150, 70, 118], 352: [123, 334], 353: [161, 196]}

s = sorted(test.values(), key=get_length, reverse=True)

It correctly sorted as desired, but this breaks my dictionary and results in:

s = [[115, 191, 226], [150, 70, 118], [235, 238], [129, 277], [194, 328], [123, 334], [161, 196]]

As you can see the keys are gone, and the data is useless for further processing.

What am I missing? Big thanks to anyone who can help me sort this out.

It looks like you have 2 levels of processing: first by key, then by length of value.

As per my comment above, the output is a list of tuples, as currently ordered dictionaries are considered an implementation detail.

If you wish to use an ordered dictionary, use collections.OrderedDict as below.

from collections import OrderedDict

test = {346: [235, 238], 347: [129, 277], 348: [115, 191, 226], 349: [194, 328], 351: [150, 70, 118], 352: [123, 334], 353: [161, 196]}

s1 = OrderedDict(sorted(test.items()))
s2 = sorted(s1.items(), key=lambda k: len(s1[k[0]]), reverse=True)

# [(348, [115, 191, 226]),
#  (351, [150, 70, 118]),
#  (346, [235, 238]),
#  (347, [129, 277]),
#  (349, [194, 328]),
#  (352, [123, 334]),
#  (353, [161, 196])]

d = OrderedDict(s2)

# OrderedDict([(348, [115, 191, 226]),
#              (351, [150, 70, 118]),
#              (346, [235, 238]),
#              (347, [129, 277]),
#              (349, [194, 328]),
#              (352, [123, 334]),
#              (353, [161, 196])])

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