从下面运行python代码时出现此错误
'dict_items' object does not support indexing
https://github.com/commodo/geonames-dump-to-sqlite/blob/master/geonames_dump_to_sqlite.py
代码的作用是从geonames中获取文件并将结果放在sqlite数据库中。
它运行正常,直到创建表
def create_tables(cur):
'''
Create empty tables which will be populated later.
'''
for table_name in TABLE_MAPPINGS.values():
cur.execute('DROP TABLE IF EXISTS %s' % table_name)
table_fields = [ "%s %s" % table_field.listitems()[0] for table_field in TABLE_FIELDS ]
cur.execute('CREATE TABLE %s (%s)' % (table_name, ','.join(table_fields)))
错误细节:
line 111, in <listcomp>
table_fields = [ "%s %s" % table_field.items()[0] for table_field in TABLE_FIELDS ]
TypeError: 'dict_items' object does not support indexing
答案 0 :(得分:1)
在Python 3中,dict.items()
返回字典视图,而不是列表对象。您可以将其转换为列表(无论如何,每个TABLE_FIELDs
条目只有一个键和值):
table_fields = [ "%s %s" % list(table_field.items())[0] for table_field in TABLE_FIELDS ]
稍后,您会遇到同样的问题,因为代码会尝试对table_field.keys()
执行相同操作:
table_fields = [ "%s" % list(table_field.keys()[0] for table_field in TABLE_FIELDS ]
将其更改为:
table_fields = [ "%s" % list(table_field)[0] for table_field in TABLE_FIELDS ]
两种用途也可分别替换为next(iter(table_field.items()))
和next(iter(table_field))
。
我不知道为什么作者在那里使用了一键词典列表;如果代码使用元组代码,它会更容易:
TABLE_FIELDS = [('parentid', 'integer'),
('geonameid', 'integer'),
('name', 'text'),
# etc.
然后分别使用% table_field
和% table_field[0]
。
然而,该脚本中可能存在其他Python 3不兼容性。