以字符串存储的键的整数值排序字典列表 [英] sort a list of dictionary by taking integer value of keys stored as string
问题描述
我有一个字典的列表,其值存储为字符串。我想通过取值作为整数而不是字符串进行排序。
代码我有
XWordDict = [{name:ABC,pos:1 },{name:GHI,pos:10},{name:DEF,pos:2}]
Xlistsorted = sorted(XWordDict,key = (operator.itemgetter(pos)))
这个顺序是
[{'name':'ABC','pos':'1'},{'name':'GHI','pos' :'10'},{'name':'DEF','pos':'2'}]
但是我想要它是
[{'name':'ABC','pos':'1' },{'name':'DEF','pos':'2'},{'name':'GHI','pos':'10'}]
/ pre>
如果我更改为
Xlistsorted = sorted(XWordDict ,key = int(operator.itemgetter(pos)))
它给出错误
TypeError:int()参数必须是字符串或数字,而不是'operator.itemgetter'
参数需要是一个函数。operator.itemgetter(i)
返回一个函数,但为了添加额外的处理,你必须使用一个lambda。因为itemgetter
返回一个函数,你可以调用结果在字典上使用它(你正在作为x
在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'}]
这就是说,
itemgetter
可能是一个过于复杂的解决方案,您可以这样做:listsorted = sorted(XWordDict,key = lambda x:int(x ['pos']))
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":"ABC","pos":"1"},{"name":"GHI","pos":"10"},{"name":"DEF","pos":"2"}] Xlistsorted=sorted(XWordDict,key=(operator.itemgetter("pos")))
This gives the order as
[{'name': 'ABC', 'pos': '1'}, {'name': 'GHI', 'pos': '10'}, {'name': 'DEF', 'pos': '2'}]
however I want it to be
[{'name': 'ABC', 'pos': '1'}, {'name': 'DEF', 'pos': '2'}, {'name': 'GHI', 'pos': '10'}]
If I change to
Xlistsorted=sorted(XWordDict,key=int(operator.itemgetter("pos)))
it gives an error
TypeError: int() argument must be a string or a number, not 'operator.itemgetter'
解决方案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. Becauseitemgetter
returns a function, you can call the result to use it on the dictionary (which you are passing as thex
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']))
这篇关于以字符串存储的键的整数值排序字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文