sort a list of dictionary by taking integer value of keys stored as string

后端 未结 2 1742
清酒与你
清酒与你 2021-01-27 03:27

I have a list of dictionaries with values stored as strings. I want to sort them by taking the values as integer not string. Code I have

 XWordDict=[{\"name\":\         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-27 04:16

    The argument to sorted()'s "key" keyword is a unary function that returns the actual value you want sorted. So you'll need a function that converts each element of the list (the dictionary which we'll call d), accesses the value you want to sort on, and converts it from a string to an integer.

    def dict_to_int(d):
        string_value = d['pos']
        int_value = int(string_value)
        return int_value
    

    You would pass this to sorted() like this:

    sorted_list = sorted(list_of_dicts, key=dict_to_int)
    

    This function is a verbose example, and can be shortened significantly and converted to a fairly concise lambda:

    lambda d: int(d['pos'])
    

    and used thus:

    sorted_list = sorted(list_of_dicts, key=lambda d: int(d['pos']))
    

提交回复
热议问题