2

I have a python dictionary

d = {
    "Random" : [1,2,3], "Stupid" :  [1], "Gross" : [1,1,1,1,1], "Ugly" : [2,1,1,1]
    }

The above list should be sorted based on the count of the list values.

I tried this : sorted(d, key=d.get, reverse=True)

But I don't seem to get the right result.

2 Answers 2

4

Do you mean length?

>>> sorted(d, key=lambda k: -len(d[k]))
['Gross', 'Ugly', 'Random', 'Stupid']
>>> sorted(d, key=lambda k: len(d[k]), reverse=True)
['Gross', 'Ugly', 'Random', 'Stupid']
Sign up to request clarification or add additional context in comments.

3 Comments

This works for me. Thanks, I need to get used to lambda . Sigh Btw why not use count instead of len /.
count counts the occurences of an item in a list, length returns the number of all items in a list
@DeepankarBajpeyi, [1,1,1,3].count(1) gives 3. len([1,1,1,3]) gives 4. If you want 3, use count.
1

Since you are starting from a dictionary presumably you need to end with one, rather than a list so:

>>> import collections
>>> d = {
...     "Random" : [1,2,3], "Stupid" :  [1], "Gross" : [1,1,1,1,1], "Ugly" : [2,1,1,1]
...     }
>>> sd = collections.OrderedDict(sorted(d.items(), key=lambda t: -len(t[1])))
>>> sd
OrderedDict([('Gross', [1, 1, 1, 1, 1]), ('Ugly', [2, 1, 1, 1]), ('Random', [1, 2, 3]), ('Stupid', [1])])
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.