Python3出现AttributeError: ‘dict’ object has no attribute错误

本文介绍如何在Python3中正确地对字典进行排序,并解释了为何不再使用iteritems方法。同时,介绍了operator模块的itemgetter函数及字典的items()方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

result = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)

错误显示

AttributeError: 'dict' object has no attribute 'iteritems'
之所以会出现上述错误是因为python3中已经没有这个属性,直接改为items即可:

result = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)

知识点补充

operator.itemgetter函数

operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。

a = [1,2,3] 
b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值
print(b(a)) 

输出: 
2
b=operator.itemgetter(1,0)   //定义函数b,获取对象的第1个域和第0个域的值
print(b(a)) 

输出: 
(2, 1)

要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。

字典items()操作方法:

x = {'title':'python web site','url':'www.iplaypy.com'}
print(x.items())

输出: 
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]

从结果中可以看到,items()方法是将字典中的每个项分别做为元组,添加到一个列表中,形成了一个新的列表容器。如果有需要也可以将返回的结果赋值给新变量,这个新的变量就会是一个列表数据类型。

a=x.items()
print(a)

输出:
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]
print(type(a))

输出: 
<\type ‘list’>

 

转自:https://blog.youkuaiyun.com/sinat_35512245/article/details/78639317

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值