以字符串存储的键的整数值排序字典列表 [英] sort a list of dictionary by taking integer value of keys stored as string

查看:164
本文介绍了以字符串存储的键的整数值排序字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典的列表,其值存储为字符串。我想通过取值作为整数而不是字符串进行排序。
代码我有

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

这篇关于以字符串存储的键的整数值排序字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆