Home > OS >  Sort python dictionary base length of values as list
Sort python dictionary base length of values as list

Time:07-19

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]
         }

CodePudding user response:

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]
}

CodePudding user response:

_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)

CodePudding user response:

use short() function to solve this

CodePudding user response:

_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.

  • Related