37

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

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

3 Answers3

84

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

Johan
  • 1,633
  • 15
  • 22
  • "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: https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects – juanpa.arrivillaga Oct 02 '19 at 22:43
9

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

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())
Klamer Schutte
  • 1,063
  • 9
  • 18
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).

Mohammad Heydari
  • 3,933
  • 2
  • 26
  • 33