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

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

    If you do not need the original list of dictionaries, you could modify it in-place with sort() method using a custom key function.

    Key function:

    def get_name(d):
        """ Return the value of a key in a dictionary. """
    
        return d["name"]
    

    The list to be sorted:

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

    Sorting it in-place:

    data_one.sort(key=get_name)
    

    If you need the original list, call the sorted() function passing it the list and the key function, then assign the returned sorted list to a new variable:

    data_two = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
    new_data = sorted(data_two, key=get_name)
    

    Printing data_one and new_data.

    >>> print(data_one)
    [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
    >>> print(new_data)
    [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
    

提交回复
热议问题