X10nD X10nD - 7 months ago 33
Python Question

Sorting Tuples throws an error - python

I am learning python and trying to sort tuples in the simplest way and its throwing errors

d = {'a':10,'b':1,'c':22}
print (d.items())

t = d.items()
print (t)

And it throws me the below error

dict_items([('b', 1), ('a', 10), ('c', 22)])
Traceback (most recent call last):
File "/Users/bash/Downloads/n.py", line 5, in <module>
AttributeError: 'dict_items' object has no attribute 'sort'

Yes, I googled and stackoverflow did not give the results I am looking for so it would be great if you dont down vote this question and give an answer if possible.


A dict doesn't have a sort attribute. You can sort it by keys using sorted:

for key in sorted(d.iterkeys()):
    print("%s: %s" % (key, d[key]))