gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:16 25 4
gpt4 key购买 nike

假设我有这样一本字典:

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'

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

最佳答案

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

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

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

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

关于python - 按字典键的整数对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23793727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com