【问题标题】:Sort dictionary by integers of dictionary keys按字典键的整数对字典进行排序
【发布时间】:2014-05-21 21:02:23
【问题描述】:

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

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,橙色”排在最后。我认为这样的事情会起作用:

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'

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

【问题讨论】:

  • itemgetter(0) 实际上是一个从.iteritems() 一次传递一个项目的函数:例如itemgetter(0)('ab') 将返回'a'。但是int(itemgetter(0))('ab') 没有意义,对吧?

标签: python sorting dictionary


【解决方案1】:

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

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

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

你得到的错误基本上告诉你不能用 operator.itemgetter(可调用)调用int(),你只能用字符串或数字调用它。

【讨论】:

  • 谢谢!太完美了。
【解决方案2】:

这是人们对itemgetter 莫名其妙的吸引力可能导致他们误入歧途的时候之一。只需使用lambda

>>> thedict={'1':'the','2':2,'3':'five','10':'orange'}
>>> sorted(thedict.iteritems(), key=lambda x: int(x[0]))
[('1', 'the'), ('2', 2), ('3', 'five'), ('10', 'orange')]

问题是int(operator.itemgetter(0)) 正在被立即评估,以便将其作为参数传递给sorted。所以你正在构建一个itemgetter,然后尝试在它上面调用int(这不起作用,因为它不是字符串或数字)。

【讨论】:

  • +1 正要发布完全相同的解决方案,但你打败了我
  • 感谢帝斯曼。 Gavin 的回答基本上是等价的,可能比你多几秒钟,所以我把答案给了他。
  • @gammapoint:不用担心!事实上,即使除了他打我一拳之外,我认为如果有两个基本相同的答案,总的来说最好给代表较低的人打勾——这有助于推动他获得新的能力网站。
猜你喜欢
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-04-17
  • 2019-01-25
  • 1970-01-01
  • 2014-02-11
  • 2012-02-18
相关资源
最近更新 更多