dict_items object has no attribute 'sort'

user960567 picture user960567 · Jan 20, 2015 · Viewed 41.9k times · Source

First of all I am new to Python. I am using PTVS http://pytools.codeplex.com/. Next I installed reportlab. Then I run a sample demo at https://github.com/nakagami/reportlab/blob/master/demos/colors/colortest.py#L68 But at line,

all_colors = reportlab.lib.colors.getAllNamedColors().items()
all_colors.sort() # alpha order by name

I am getting error, dict_items object has no attribute sort

Answer

Johan picture Johan · Jan 20, 2015

Haven't tested but a theory: you are using python3!

From https://docs.python.org/3/whatsnew/3.0.html

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).

as I understand it a "view" is an iterator, and an iterator does not have the sort function. Change it to

sorted(all_colors)

according to the documentation