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)
a = [{'name':'Homer', 'age':39}, ...]
# This changes the list aa.sort(key=lambda k : k['name'])
# This returns a new list (a is not modified)sorted(a, key=lambda k : k['name'])
import randomimport 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 ordersorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))True