当前位置: 代码迷 >> python >> 获取类型错误:在将数据插入 postgres 时,列表索引必须是整数或切片,而不是字符串
  详细解决方案

获取类型错误:在将数据插入 postgres 时,列表索引必须是整数或切片,而不是字符串

热度:107   发布时间:2023-06-19 09:25:03.0

我正在尝试使用列表理解和 morgify 将数据推送到 postgres 中,但是我收到了错误。

实际上,排序是以下格式的字典:

sort = {'forecast': [{'name': some_value, 'search_volume': some_int_value, 
'competition': some_float_value}]}

data_text = ','.join(c.mogrify(
    "(%(k)s,%(l['name'])s,l['search_volume'],l['competition'])",
    l) for l in [v for k,v in sort.items()])

错误:

Traceback (most recent call last):
  File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 137, in get_lsi
    expand(current_word)
  File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 121, in expand
    sorted_data = write_to_file(current_results, current_word)
  File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 107, in write_to_file
    l) for l in [v for k,v in sort.items()])
  File "/Users/lonewolf/PycharmProjects/seo_keyword_research_tools-master/keyword_expansion_tool.py", line 107, in <genexpr>
    l) for l in [v for k,v in sort.items()])
TypeError: list indices must be integers or slices, not str

您可以将语法更改为:

c.mogrify(
    "(%(k)s,%(name)s,%(search_volume)s,%(competition)s",
    {'k': k, 'name': l['name'],
     'search_volume': l['search_volume'],
     'competition': l['competition'] })

通过传递所需的值,而不是对象。

注意,这似乎不是一个有效的 SQL 表达式,它应该作为psycopg的的第一个参数