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

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

    Here is the alternative general solution - it sorts elements of a dict by keys and values.

    The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.

    def sort_key_func(item):
        """ Helper function used to sort list of dicts
    
        :param item: dict
        :return: sorted list of tuples (k, v)
        """
        pairs = []
        for k, v in item.items():
            pairs.append((k, v))
        return sorted(pairs)
    sorted(A, key=sort_key_func)
    

提交回复
热议问题