Sorting Dictionaries by Key Value

  • Share this:

Code introduction


This function accepts a list of dictionaries as input and sorts the list based on the value of a specified key in each dictionary. If the specified key does not exist, an empty string is returned.


Technology Stack : List comprehension, built-in sorting method, dictionary

Code Type : Sort function

Code Difficulty : Intermediate


                
                    
def aord(str_list):
    # 排序字符串列表中的字典,按照字典中某个键的值进行排序
    # 使用了内置的排序方法和列表推导式

    def get_value(d, key):
        # 辅助函数,从字典中获取指定键的值
        return d.get(key, '')

    return sorted(str_list, key=get_value)