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\":\
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']))