简体   繁体   English

使用Python在字典值中的元组列表中对项目进行排序

[英]Sort an item in a list of tuples in the values of a dictionary with Python

I'm trying to sort the first item in a list of tuples in the value of a dictionary. 我正在尝试在字典的值中对元组列表中的第一项进行排序。

Here is my dictionary: 这是我的字典:

d = {'key_': (('2', 'a'), ('3', 'b'), ('4', 'c'), ('1', 'd'))}

I want the sorted output to look like this: 我希望排序后的输出看起来像这样:

d2 = {'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}

I tried sorting the values to a new dictionary, but that doesn't work: 我尝试将值排序到新字典中,但这不起作用:

d2 = sorted(d.values(), key=lambda x: x[0])

d.values() return the list of all the values present within the dictionary. d.values()返回字典中存在的所有值的列表。 But here you want to sort the list which is present as value corresponding to key_ key. 但是在这里您要对列表进行排序,该列表以与key_ key相对应的值的形式出现。 So, you have to call the sorted function as: 因此,必须将排序后的函数调用为:

# Using tuple as your example is having tuple instead of list
>>> d['key_'] = tuple(sorted(d['key_'], key=lambda x: x[0]))
>>> d
{'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}

Alternatively (not suggested), you may also directly sort the list without calling the sorted function as: 另外(不建议),您也可以直接对列表进行排序,而无需调用sorted函数,如下所示:

>>> d['key_'] = list(d['key_']).sort(key=lambda x: x[0])
{'key_': (('1', 'd'), ('2', 'a'), ('3', 'b'), ('4', 'c'))}

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

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