如何按特定键的值对词典列表进行排序?鉴于:

[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]

按名称排序时,应为:

[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]

当前回答

这是另一种通用解决方案——它按键和值对dict的元素进行排序。

它的优点是不需要指定键,如果某些字典中缺少一些键,它仍然可以工作。

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)
sorted(A, key=sort_key_func)

其他回答

使用来自Perl的Schwartzian变换,

py = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

do

sort_on = "name"
decorated = [(dict_[sort_on], dict_) for dict_ in py]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]

给予

>>> result
[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]

有关Perl Schwartzian转换的更多信息:

在计算机科学中,施瓦茨变换是一种Perl编程用于提高项目列表排序效率的习惯用法。这当排序为实际上基于元素,其中计算该属性是一项密集的操作应执行最少次数。施瓦茨学派Transform的显著之处在于它不使用命名的临时数组。

我猜你的意思是:

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

其排序如下:

sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))

使用Pandas包是另一种方法,尽管其大规模运行时比其他人提出的更传统的方法慢得多:

import pandas as pd

listOfDicts = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
df = pd.DataFrame(listOfDicts)
df = df.sort_values('name')
sorted_listOfDicts = df.T.to_dict().values()

下面是一个小列表和一个大(100k+)的字典列表的一些基准值:

setup_large = "listOfDicts = [];\
[listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10})) for _ in range(50000)];\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listOfDicts);"

setup_small = "listOfDicts = [];\
listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}));\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(listOfDicts);"

method1 = "newlist = sorted(listOfDicts, key=lambda k: k['name'])"
method2 = "newlist = sorted(listOfDicts, key=itemgetter('name')) "
method3 = "df = df.sort_values('name');\
sorted_listOfDicts = df.T.to_dict().values()"

import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method LC2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))

t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method LC2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup_large)
print('Large Method Pandas: ' + str(t.timeit(1)))

#Small Method LC: 0.000163078308105
#Small Method LC2: 0.000134944915771
#Small Method Pandas: 0.0712950229645
#Large Method LC: 0.0321750640869
#Large Method LC2: 0.0206089019775
#Large Method Pandas: 5.81405615807
a = [{'name':'Homer', 'age':39}, ...]

# This changes the list a
a.sort(key=lambda k : k['name'])

# This returns a new list (a is not modified)
sorted(a, key=lambda k : k['name']) 

sorted()函数接受key=参数

newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) 

或者,您可以使用operator.itemgetter而不是自己定义函数

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

为完整起见,添加reverse=True以降序排序

newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)