如何按字典的值对字典列表进行排序?

我有一个字典列表,希望每个项目都按特定值排序。

考虑列表:

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

当按name排序时,它应该变成:

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

Here is the alternative general solution - it sorts elements of a dict by keys and values.

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)

sorted(A, key=sort_key_func)


Let's say I have a dictionary D with the elements below. To sort, just use the key argument in sorted to pass a custom function as below:

D = {'eggs': 3, 'ham': 1, 'spam': 2}
def get_count(tuple):
    return tuple[1]

sorted(D.items(), key = get_count, reverse=True)

Or

sorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call

Check this out.

If performance is a concern, I would use operator.itemgetter instead of lambda as built-in functions perform faster than hand-crafted functions. The itemgetter function seems to perform approximately 20% faster than lambda based on my testing.

From https://wiki.python.org/moin/PythonSpeed:

Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).

Here is a comparison of sorting speed using lambda vs itemgetter.

import random
import operator

Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.

l = [{‘name’: ‘’.join(random.choices(string.ascii_lowercase, k=8)), ‘age’: random.randint(0, 100)} for i in range(100)]

Test the performance with a lambda function sorting on name

%timeit sorted(l, key=lambda x: x[‘name’])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Test the performance with itemgetter sorting on name

%timeit sorted(l, key=operator.itemgetter(‘name’))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Check that each technique produces the same sort order

sorted(l, key=lambda x: x[‘name’]) == sorted(l, key=operator.itemgetter(‘name’))
True

Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.