简体   繁体   中英

Sort python dictionary base length of values as list

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

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

使用 short() 函数来解决这个问题

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

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