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

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

提交回复
热议问题