dict_items 对象没有属性 'sort'

dict_items object has no attribute 'sort'

首先我是 Python 的新手。我正在使用 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 但在线,

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

我遇到错误,dict_items object has no attribute sort

没测试过,只是一个理论:你用的是python3!

来自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).

据我理解,"view"是迭代器,迭代器没有排序功能。将其更改为

sorted(all_colors)

根据文档

所以基于 Johan 的答案的总解决方案是:

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())

我认为 sort() 方法不再支持 Python 3.x

需要将相应的变量传递给sorted(all_colors)