Simplicity Simplicity - 1 year ago 62
Python Question

Printing the dictionary sorted by value

I'm trying to print the dictionary sorted by its

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 "", 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?


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download