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 key
argument needs to be a function. operator.itemgetter(i)
returns a function, but in order to add extra processing on top of that, you'll have to use a lambda. Because itemgetter
returns a function, you can call the result to use it on the dictionary (which you are passing as the x
in the lambda:
listsorted = sorted(XWordDict, key=lambda x: int(operator.itemgetter("pos")(x)))
listsorted
Out[16]:
[{'name': 'ABC', 'pos': '1'},
{'name': 'DEF', 'pos': '2'},
{'name': 'GHI', 'pos': '10'}]
That said, itemgetter
might be an overly complex solution here, you can just do:
listsorted = sorted(XWordDict, key=lambda x: int(x['pos']))