When the wrong code comes up :
result = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
Error display :
AttributeError: 'dict' object has no attribute 'iteritems'
The reason for the above error is python3 There is no such attribute in , Directly change to items that will do :
result = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
Knowledge points supplement :
operator.itemgetter function
operator Module provided itemgetter Function is used to get the data of which dimensions of an object , The parameter is some sequence number ( That is, the serial number of the data to be acquired in the object ), Let's take an example .
a = [1,2,3]
b=operator.itemgetter(1) // Defined function b, Get the... Of the object 1 Values for domains
print(b(a))
Output :
2
b=operator.itemgetter(1,0) // Defined function b, Get the... Of the object 1 Domain and the 0 Values for domains
print(b(a))
Output :
(2, 1)
it is to be noted that ,operator.itemgetter Function does not get value , It defines a function , This function is used to get the value of an object .
Dictionaries items() Operation method :
x = {
'title':'python web site','url':'www.iplaypy.com'}
print(x.items())
Output :
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]
You can see from the results ,items() The method is to treat each item in the dictionary as a tuple , Add to a list , Form a new list container . If necessary, you can also assign the returned result to the new variable , This new variable will be a list data type .
a=x.items()
print(a)
Output :
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]
print(type(a))
Output :
<\type ‘list’>
Reference material :Python Dictionaries items Returns a list of