简体   繁体   中英

In Python, given a dictionary with lists in the values, how do I sort the dictionary based on the amount of items in that list?

I have a dictionary

d={'a': ['apple'], 'd': ['dog', 'dance', 'dragon'], 'r': ['robot'], 'c': ['cow', 'cotton']}

and I want to define a function that will order them by the size of the set. That is, since "d" has 3 items in the value, "c" has 2 items, and "a" and "r" each have one item, I want a dictionary in that order. So

d={'d': ['dog', 'dance', 'dragon'], 'c': ['cow', 'cotton'], 'a': ['apple'],  'r': ['robot']}

What I have so far is

def order_by_set_size(d):
    return sorted(d, key=lambda k: len(d[k]), reverse=True)

This gives me a list, but I can't figure out how to have it give me a dictionary. I've looked at a lot of other questions and tried different variations of code and this is as close as I can get.

(I'm using Python 3)

you need to use an OrderedDict see https://docs.python.org/3/library/collections.html#collections.OrderedDict

Based on their example

from collections import OrderedDict

d={'a': ['apple'], 'd': ['dog', 'dance', 'dragon'], 'r': ['robot'], 'c': ['cow', 'cotton']}
ordered = OrderedDict(sorted(d.items(),key=lambda t: len(t[1]),reverse=True))

Dictionaries are, by definition, unordered key-value pairs. Therefore, the code below is correct, as you can only get a list if you want it to be sorted. In other words, dictionaries cannot be sorted, so the task given is impossible.

def order_by_set_size(d):
    return sorted(d, key=lambda k: len(d[k]), reverse=True)

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