按字典键的整数对字典进行排序

2023-12-12

假设我有一本这样的字典:

thedict={'1':'the','2':2,'3':'five','10':'orange'}

我想按键对这本字典进行排序。如果我执行以下操作:

for key,value in sorted(thedict.iteritems()):
     print key,value

我将获得

1 the
10 orange
2 2
3 five

因为键是字符串而不是整数。我想对它们进行排序,就好像它们是整数一样,因此条目“10,orange”排在最后。我认为这样的事情会起作用:

for key,value in sorted(thedict.iteritems(),key=int(operator.itemgetter(0))):
    print key,value

但这产生了这个错误:

TypeError: int() argument must be a string or a number, not 'operator.itemgetter'

我在这里做错了什么?谢谢!


我认为你可以使用 lambda 表达式轻松做到这一点:

sorted(thedict.iteritems(), key=lambda x: int(x[0]))
# with Python3, use thedict.items() for an iterator

问题是你正在将一个可调用对象传递给int()内置并尝试使用的返回值int()作为键的可调用对象进行调用。您需要为关键参数创建一个可调用对象。

您收到的错误基本上告诉您无法调用int()使用operator.itemgetter(可调用),您只能使用字符串或数字来调用它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按字典键的整数对字典进行排序 的相关文章

随机推荐