简体   繁体   English

Python:根据元组值对字典进行排序。 清单输出

[英]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 假设我想根据元组值中的第一个索引对它进行排序(如果使用apple键,它将是数字8)。所以我希望我的输出是

["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] : 不知道是否找到答案,但是以下代码将返回按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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM