Reputation: 55
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)
Upvotes: 2
Views: 55
Reputation: 1825
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))
Upvotes: 2
Reputation: 134
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)
Upvotes: 0