I have a list of dictionaries and want each item to be sorted by a specific value.
Take into consideration the list:
[{\'name\':\'Homer\', \'age\':39},
I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.
sorted_list = sorted(list_to_sort, key= lambda x: x['name'])
# Returns list of values
list_to_sort.sort(key=operator.itemgetter('name'))
# Edits the list, and does not return a new list
# First option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" "sorted_l = sorted(list_to_sort, key=lambda e: e['name'])"
1000000 loops, best of 3: 0.736 µsec per loop
# Second option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" -s "import operator" "list_to_sort.sort(key=operator.itemgetter('name'))"
1000000 loops, best of 3: 0.438 µsec per loop