Analysis and resolution of error AttributeError: 'dict' object has attribute 'iteritems

  • 2020-06-07 04:48:58
  • OfStack

The introduction

There are currently version incompatibilities between Python2 and Python3, and issue 1 of dict is listed here. Without further ado, let's take a look at the details:

1. Python 2 vs python 3

According to the mainstream requirements of the Python community, Python 2 will not provide technical support in the next few years. The current python 2.7.12 is its maintenance version. If there are no accidents, please refer to Python 3.

The split and downward incompatibility between Python 3 and Python 2 is one of its best-known events, causing considerable distress to the community and related applications.

Problem 2.

Python 2:

> > dict1 = {}

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

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

print(k+ "= > " + v)


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. Problem solving

Confirm its usage under Python 3:

Use under Python 2 is:


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

The above code runs correctly under python3.

4. Python 2 vs python 3

Python from Python 2 3 needs a process, the evolution of the difference of them can refer to the following articles: https: / / www ofstack. com article / 105518. htm

conclusion


Related articles: