dict_items object has no attribute 'sort'
Asked Answered
O

3

39

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

Ottoman answered 20/1, 2015 at 6:38 Comment(0)
K
86

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

Keratitis answered 20/1, 2015 at 7:10 Comment(1)
"as I understand it a "view" is an iterator" It is not, but the view is iterable. A view is basically a proxy object that so you can get an object representing the items in dict with constant space/time overhead. This is frequently used to iterate over key-value pairs in a dict, yes, but it also supports other handy methods, like set-like operations. Read more here: docs.python.org/3/library/stdtypes.html#dictionary-view-objectsAloeswood
Z
9

So the total solution based on Johan's answer is:

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())
Zolner answered 26/10, 2016 at 11:28 Comment(0)
R
3

I believe the sort() method doesn't support Python 3.x anymore.

It is necessary to pass the corresponding variable to the sorted(all_colors).

Ruche answered 2/10, 2019 at 22:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.