geonames-dump to sqlite python 错误 'dict_items' 对象不支持索引

geonames-dump to sqlite python error 'dict_items' object does not support indexing

当运行下面的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

在Python3中,dict.items()returns是字典视图,不是列表对象。您可以在此处将其转换为列表(无论如何每个 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 个不兼容性。