简体   繁体   中英

Python: Sort dictionary based on tuple value. List output

I would like to sort a dictionary based on one of the tuple values. Consider the following dictionary example:

my_dict = {"apple": (8, 1023), "ant": (3, 29883), "zebra": (4, 489)}

Say I would like to sort it based on the first index in the tuple value in the case of the apple key it would be the number 8. So I'd expect my output to be

["ant", "zebra", "apple"]

I know I could use something like

 x = sorted(my_dict, key = my_dict.get)

But as you can guess, that doesn't work for tuple/list values. Any help would be appreciated!

What about this:

>>> my_dict = {"apple": (8, 1023), "ant": (3, 29883), "zebra": (4, 489)}
>>> sorted(my_dict,key=lambda k: my_dict[k][0])
['ant', 'zebra', 'apple']

Not sure if you found the answer but the code below will return your dictionary sorted by tuple[0] :

sorted_dict = []
my_dict = {"apple": (8, 1023), "ant": (3, 29883), "zebra": (4, 489)}
my_dict_copy = sorted(my_dict.items(),key=lambda x: x[1][0])
for i in my_dict_copy:
    sorted_dict.append(i[0])

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