1

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

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

t = d.items()
t.sort()
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>
    t.sort()
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.

Frederico Martins
  • 1,081
  • 1
  • 12
  • 25
X10nD
  • 21,638
  • 45
  • 111
  • 152

2 Answers2

4

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]))
Frederico Martins
  • 1,081
  • 1
  • 12
  • 25
  • I'd also note that `sorted()` can be used with dict_item objects, so all the asker really needed to do with his code was change `t.sort()` to `t = sorted(t)`. – glibdud Aug 31 '16 at 12:38
3

Here's the thing, your original code works in python 2.x:

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

t = d.items()
t.sort()
print(t)

Because d.items() returns a <type 'list'> class, but not with python 3.x, with python 3.x it returns <class 'dict_items'>, which doesn't have the sort method, so a possible workaround would be doing like this:

d = {'a': 10, 'b': 1, 'c': 22}

t = list(d.items())
print(t)
t.sort()
print(t)

As you can see, casting d.items() to list will allow you to use list.sort

BPL
  • 9,632
  • 9
  • 59
  • 117