-2

I have a python dictionary with values as list of integers. I want to sort it in descending order based on the length of the values which is list

_dict = {
         'owner_1': [320, 203, 123, 32, 923, 12398], 
         'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
                    9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
         'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
                    9219, 239, 9021092, 9294]
         }

The output should be like

_dict = {
         'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
                     9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
         'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
                     9219, 239, 9021092, 9294], 
         'owner_1': [320, 203, 123, 32, 923, 12398]
         }
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • 2
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Sandeep Rawat Jul 19 '22 at 06:30

3 Answers3

3

You can use sorted on dict.items() and use len for value of dict.

>>> dict(sorted(_dict.items(), key=lambda x: len(x[1]), reverse=True))
# --------------------------------------x[0] is key, x[1] is value of each item dict
{
    'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
    'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 9219, 239, 9021092, 9294], 
    'owner_1': [320, 203, 123, 32, 923, 12398]
}
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1
_dict = {
         'owner_1': [320, 203, 123, 32, 923, 12398], 
         'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
                    9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
         'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
                    9219, 239, 9021092, 9294]
         }
    

sorted_dict = {}
for k in sorted(_dict, key=lambda k: len(_dict[k]), reverse=True):
    sorted_dict[k] = _dict[k]
    
print(sorted_dict)
1
_dict = {
         'owner_1': [320, 203, 123, 32, 923, 12398], 
         'owner_2': [239, 90, 3423, 234, 3994, 93294, 923849, 939, 312, 2341, 93, 
                    9244, 294, 939532, 9284, 9113, 34, 98934, 9293, 83], 
         'owner_3': [2399, 934, 8231, 921338, 9394, 9023, 92, 911, 934, 983912, 
                    9219, 239, 9021092, 9294]
         }


{key:value for key,value in sorted(_dict.items(), key = lambda x: len(x[1]), reverse=True)}

This is a one-liner to sort your dictionary according to the values. Key is x[0] ('owner_1', 'owner_2' etc) and the value is the length of x[1] or the number of items in the list corresponding to the key. Finally reverse= True prints the dictionary in reverse order.

AU_97_CB
  • 27
  • 10