您的位置:首页 > 移动开发 > Objective-C

Python3下AttributeError: 'dict' object has no attribute 'iteritems'的问题分析

2017-05-31 19:35 1176 查看
引言: 目前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)

[html] view plain copy print?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’


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之下的用法是:

[html] view plain copy print?for k, v in dict1.iteritems():
print(k+ ”=>“ + v)


for k, v in dict1.iteritems():
print(k+ "=>" + v)
上述代码在python3下,可以正确的执行运行。
4. Python 2 vs python 3
从Python 2向Python 3的进化需要一个过程,其中的差异可以参照如下文章: https://www.zhihu.com/question/19698598
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐