如何按特定键的值对词典列表进行排序?鉴于:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
按名称排序时,应为:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
如何按特定键的值对词典列表进行排序?鉴于:
[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
按名称排序时,应为:
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
当前回答
使用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
其他回答
我猜你的意思是:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
其排序如下:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
如果不需要字典的原始列表,可以使用自定义键函数使用sort()方法对其进行修改。
关键功能:
def get_name(d):
""" Return the value of a key in a dictionary. """
return d["name"]
要排序的列表:
data_one = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
将其分类到位:
data_one.sort(key=get_name)
如果需要原始列表,请调用sorted()函数,将列表和键函数传递给它,然后将返回的排序列表分配给新变量:
data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
new_data = sorted(data_two, key=get_name)
正在打印data_one和new_data。
>>> print(data_one)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
>>> print(new_data)
[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
使用来自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的显著之处在于它不使用命名的临时数组。
使用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
您可以使用以下选项:
lst = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
sorted_lst = sorted(lst, key=lambda x: x['age']) # change this to sort by a different field
print(sorted_lst)