[英]How do I sort a list of dictionaries by more than one element
This thread How do I sort a list of dictionaries by values of the dictionary in Python? 此线程如何按Python中字典的值对字典列表进行排序? explains very clearly how to sort a list of dictionaries.
非常清楚地解释了如何对字典列表进行排序。 In summary for,
总结一下,
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
You do: 你做:
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
However, I have much more elements in my dictionary and I need to sort by four of them - not just one. 但是,我的字典中有更多的元素,我需要按其中的四个来排序 - 而不仅仅是一个。 Any tips how to do this?
任何提示如何做到这一点?
Note: I read further into the thread and this suggestion: 注意:我进一步阅读了线程和这个建议:
sortedlist = sorted(input, key=lambda elem: "%02d %s" % (elem['age'], elem['name']))
does not work. 不起作用。 It gives error:
它给出了错误:
TypeError: list indices must be intergers, not str
I try various versions of this and to no avail. 我尝试了各种版本但无济于事。
Any help appreciated, 任何帮助,赞赏,
Simply change the key function to return a tuple containing the elements you wish to sort by: 只需更改键功能即可返回包含您要排序的元素的元组:
newlist = sorted(input, key=lambda k: (k['age'], k['name']))
For example: 例如:
In [13]: input = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Milhouse', 'age':10}, {'name': 'Mr. Burns', 'age': 104}]
In [14]: sorted(input, key=lambda k: (k['age'], k['name']))
Out[14]:
[{'age': 10, 'name': 'Bart'},
{'age': 10, 'name': 'Milhouse'},
{'age': 39, 'name': 'Homer'},
{'age': 104, 'name': 'Mr. Burns'}]
Your approach with string formatting could also be made to work, but the number of digits in the format would need to be increased to accommodate the likes of Cornelius Chapman . 您的字符串格式化方法也可以使用,但需要增加格式中的位数以适应Cornelius Chapman等 。 ;-)
;-)
Having said that, I would recommend using a tuple, as this tackles the problem more directly, is more efficient and is less prone to coding errors. 话虽如此,我建议使用元组,因为这可以更直接地解决问题,更有效并且不易出现编码错误。
edit: As suggested by @JBernardo in the comments, the above can also be phrased using operator.itemgetter()
: 编辑:正如@JBernardo在评论中所建议的,上面也可以使用
operator.itemgetter()
来表达:
In [19]: sorted(input, key=operator.itemgetter('age','name'))
Out[19]:
[{'age': 10, 'name': 'Bart'},
{'age': 10, 'name': 'Milhouse'},
{'age': 39, 'name': 'Homer'},
{'age': 104, 'name': 'Mr. Burns'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.