脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3下错误AttributeError: ‘dict’ object has no attribute’iteritems‘的分析与解决

Python3下错误AttributeError: ‘dict’ object has no attribute’iteritems‘的分析与解决

2020-11-24 00:13bladestone Python

这篇文章主要跟大家介绍了关于在Python3下错误AttributeError: 'dict' object has no attribute 'iteritems'的分析与解决方法,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。

引言

目前Python2和Python3存在版本上的不兼容性,这里将列举dict中的问题之一。下面话不多说,来看看详细的介绍:

1. Python 2  vs python 3

根据Python社区的主流要求,Python 2将在最近的若干年内不再提供技术支持,目前的python 2.7.12已经是其维护版本;如无意外,大家请参照使用Python 3.

Python 3与Python 2之间的割裂以及向下不兼容性是其一个非常著名的事件,给整个社区和相关应用造成了相当的困扰。

2.  问题

     Python 2:

      >>  dict1 = {}

     >>  dict1['key1'] = 'val1'

    >>   for k, v in dict1.items():

               print(k+ "=>" + v)

?
1
2
3
4
5
6
Traceback (most recent call last):
 
 File "<ipython-input-23-5ccef53f3d75>", line 1, in <module>
 hist_sorted = sorted(hist.iteritems(), key=lambda d: d[1], reverse=True)
 
AttributeError: 'dict' object has no attribute 'items'

3.  问题的解决

确认其为Python 3下的用法:

在Python 2之下的用法是:

?
1
2
for k, v in dict1.iteritems():
    print(k+ "=>" + v)

上述代码在python3下,可以正确的执行运行。

4.  Python 2 vs python 3

从Python 2向Python 3的进化需要一个过程,其中的差异可以参照如下文章:http://www.zzvips.com/article/105709.html

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://blog.csdn.net/blueheart20/article/details/54600511

延伸 · 阅读

精彩推荐