[英]Python: How to sort a list of dictionaries by several values?
I want to sort a list at first by a value and then by a second value.我想首先按一个值对列表进行排序,然后再按第二个值排序。 Is there an easy way to do this?是否有捷径可寻? Here is a small example:这是一个小例子:
A = [{'name':'john','age':45},
{'name':'andi','age':23},
{'name':'john','age':22},
{'name':'paul','age':35},
{'name':'john','age':21}]
This command is for sorting this list by 'name'
:此命令用于按'name'
对该列表进行排序:
sorted(A, key = lambda user: user['name'])
But how I can sort this list by a second value?但是我如何按第二个值对这个列表进行排序? Like 'age'
in this example.就像这个例子中的'age'
。
I want a sorting like this (first sort by 'name'
and then sort by 'age'
):我想要这样的排序(首先按'name'
排序,然后按'age'
排序):
andi - 23
john - 21
john - 22
john - 45
paul - 35
Thanks!谢谢!
>>> A = [{'name':'john','age':45},
{'name':'andi','age':23},
{'name':'john','age':22},
{'name':'paul','age':35},
{'name':'john','age':21}]
>>> sorted(A, key = lambda user: (user['name'], user['age']))
[{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}]
This sorts by a tuple of the two attributes, the following is equivalent and much faster/cleaner:这按两个属性的元组排序,以下等效且更快/更清晰:
>>> from operator import itemgetter
>>> sorted(A, key=itemgetter('name', 'age'))
[{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}]
From the comments: @Bakuriu来自评论:@Bakuriu
I bet there is not a big difference between the two, but
itemgetter
avoids a bit of overhead because it extracts the keys and make thetuple
during a single opcode(CALL_FUNCTION
), while calling thelambda
will have to call the function, load the various constants(which are other bytecodes) finally call the subscript (BINARY_SUBSCR
), build thetuple
and return it... that's a lot more work for the interpreter.我敢打赌两者之间没有太大区别,但是itemgetter
避免了一点开销,因为它在单个操作码(CALL_FUNCTION
)期间提取键并生成tuple
,而调用lambda
将不得不调用该函数,加载各种常量(其他字节码)最终调用下标(BINARY_SUBSCR
),构建tuple
并返回它......这对解释器来说还有很多工作。
To summarize: itemgetter
keeps the execution fully on the C
level, so it's as fast as possible.总结一下: itemgetter
将执行完全保持在C
级别,因此它尽可能快。
from operator import itemgetter
sorted(your_list, key=itemgetter('name', 'age'))
Here is the alternative general solution - it sorts elements of dict by keys and values.这是替代的通用解决方案 - 它按键和值对 dict 的元素进行排序。 The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.它的优点 - 无需指定键,如果某些字典中缺少某些键,它仍然可以工作。
def sort_key_func(item):
""" helper function used to sort list of dicts
:param item: dict
:return: sorted list of tuples (k, v)
"""
pairs = []
for k, v in item.items():
pairs.append((k, v))
return sorted(pairs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.