0

从下面运行python代码时出现此错误

'dict_items' object does not support indexing

https://github.com/commodo/geonames-dump-to-sqlite/blob/master/geonames_dump_to_sqlite.py

代码所做的是从地理名称中获取文件并将结果放入 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
4

1 回答 1

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 不兼容性。

于 2015-02-27T17:01:05.940 回答