简体   繁体   中英

How to sort dictionary where value is a list in python

this is my dictionary:

mydict = {
    'item_1': [7,19],
    'item_2': [0,3],
    'item_3': [54,191],
    'item_4': [41,43]
}

and I want to sort it by values so that times with the biggest difference of the two elements in the list are placed first.

This is what I want:

mydict = {
    'item_3': [54,191],
    'item_1': [7,19],
    'item_2': [0,3],
    'item_4': [41,43],
}

How would I go about doing this?

Edit:

I got a response with this

{k: v for k, v in sorted(mydict.items(), key=lambda item: abs(item[1][0]-item[1][1]),reverse=True)}

And I also read some documentation on it, but don't understand the logic, what exactly is happening here?

You cannot sort a dictionary, but you can sort keys by a certain property of values :

sorted_keys = sorted(mydict.keys(), 
                     key=lambda x: abs(mydict[x][0]-mydict[x][1]), 
                     reverse=True)

你可以试试这个:

{k: v for k, v in sorted(mydict.items(), key=lambda item: abs(item[1][0]-item[1][1]),reverse=True)}

如前所述,字典没有排序,但是您可以获得表示字典键值对的两项元组的排序列表:

sorted_dict = sorted(mydict.items(), key=lambda item: abs(item[1][0] - item[1][1]), reverse=True)

since python3.6 dictionaries are insertion ordered (dictionaries remember the order of items inserted), so if you have a python version >=3.6 you can use:

dict(sorted(mydict.items(), key=lambda t: abs(t[1][0] - t[1][1]), reverse=True))

output:

{'item_3': [54, 191], 'item_1': [7, 19], 'item_2': [0, 3], 'item_4': [41, 43]}

for other versions of python <3.6 you can use OrderDict

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