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

后端 未结 2 1743
清酒与你
清酒与你 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条回答
  •  离开以前
    2021-01-27 04:02

    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']))
    

提交回复
热议问题