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

后端 未结 18 2863
半阙折子戏
半阙折子戏 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:44

    I guess you've meant:

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

    This would be sorted like this:

    sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
    
    0 讨论(0)
  • 2020-11-21 04:46
    a = [{'name':'Homer', 'age':39}, ...]
    
    # This changes the list a
    a.sort(key=lambda k : k['name'])
    
    # This returns a new list (a is not modified)
    sorted(a, key=lambda k : k['name']) 
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 04:49

    You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.

    You could do it this way:

    def mykey(adict): return adict['name']
    x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
    sorted(x, key=mykey)
    

    But the standard library contains a generic routine for getting items of arbitrary objects: itemgetter. So try this instead:

    from operator import itemgetter
    x = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]
    sorted(x, key=itemgetter('name'))
    
    0 讨论(0)
  • 2020-11-21 04:50
    import operator
    a_list_of_dicts.sort(key=operator.itemgetter('name'))
    

    'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.

    0 讨论(0)
  • 2020-11-21 04:50

    Using the Schwartzian transform from Perl,

    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]
    

    gives

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

    More on the Perl Schwartzian transform:

    In computer science, the Schwartzian transform is a Perl programming idiom used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when the ordering is actually based on the ordering of a certain property (the key) of the elements, where computing that property is an intensive operation that should be performed a minimal number of times. The Schwartzian Transform is notable in that it does not use named temporary arrays.

    0 讨论(0)
提交回复
热议问题