How do I sort a list of dictionaries by a value of the dictionary?

后端 未结 18 2795
半阙折子戏
半阙折子戏 2020-11-21 04:06

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},         


        
18条回答
  •  盖世英雄少女心
    2020-11-21 04:46

    I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.

    First option

    sorted_list = sorted(list_to_sort, key= lambda x: x['name'])
    # Returns list of values
    

    Second option

    list_to_sort.sort(key=operator.itemgetter('name'))
    # Edits the list, and does not return a new list
    

    Fast comparison of execution times

    # 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

提交回复
热议问题