dict_items对象没有属性'sort'

问题描述 投票:18回答:2

首先,我是Python新手。我正在使用PTVS http://pytools.codeplex.com/。接下来我安装了reportlab。然后我在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

python reportlab ptvs
2个回答
39
投票

没有测试但是理论:你正在使用python3!

来自https://docs.python.org/3/whatsnew/3.0.html

dict方法dict.keys(),dict.items()和dict.values()返回“views”而不是列表。例如,这不再有效:k = d.keys(); k.sort()。使用k = sorted(d)代替(这也适用于Python 2.5,效率也很高)。

据我所知,“视图”是一个迭代器,而迭代器没有sort函数。将其更改为

sorted(all_colors)

根据文件


5
投票

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

all_colors = sorted(reportlab.lib.colors.getAllNamedColors().items())
© www.soinside.com 2019 - 2024. All rights reserved.