设为首页 加入收藏

TOP

Python3下AttributeError: 'dict' object has no attribute 'iteritems'的问题分析
2019-04-15 14:54:16 】 浏览:34
Tags:Python3 AttributeError: ' dict' object has 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. Traceback(mostrecentcalllast):
  2. File”<ipython-input-23-5ccef53f3d75>“,line1,in<module>
  3. hist_sorted=sorted(hist.iteritems(),key=lambdad:d[1],reverse=True)
  4. AttributeError:‘dict’objecthasnoattribute‘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之下的用法是:

  1. fork,vindict1.iteritems():
  2. 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问题:NameError: name .. 下一篇Python:在Windows 10中搭建Pytho..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目