Simplicity Simplicity - 6 months ago 15
Python Question

Printing the dictionary sorted by value

I'm trying to print the dictionary sorted by its

value
in this code portion:

for key,value in frequency.items():
output = key + ' : ' + str(value)

sorted_output = sorted(output.items(), key=operator.itemgetter(1))
print sorted_output


When I try to run the program, I get the following:

Traceback (most recent call last):
File "test.py", line 16, in <module>
sorted_output = sorted(output.items(), key=operator.itemgetter(1))
AttributeError: 'str' object has no attribute 'items'


How can I solve this issue?

Thanks.

Answer

You are converting the key value pair to string and string doesn't have .items() . So it is giving the error.

Try this:

from operator import itemgetter    
for k, v in sorted(frequency.items(), key=itemgetter(1)):
        print k, v