如何使用 Python 将字符串转换为整数并加载到 Postgres 中?
How to convert String to integer and load into Postgres using Python?
我有一条记录存储在data3
这是一个字符串
data3 = ['{"Project_id": "300","Your Design Score ": "N/A"}']
同时插入我的 table
cur.executemany("""INSERT INTO TABLE3_ES(Project_id,Your_Design_Score) VALUES (%(Project_id)s, %(Your Design Score )s)""", data3)
抛出错误:
TypeError: string indices must be integers, not str
我应该如何转换数据并将其加载到我的 table 中?
Oups,你的 sql executemany
需要一个可迭代的字典,而你给它一个可迭代的字符串。正确的方法是修复获取 data3 的方式,但如果不能这样做,则必须 eval 字符串来构建字典。由于 eval
是邪恶的 如果您的实际数据可以由它处理,您应该尝试使用 ast.literal_eval
。
在示例用例中,您应该能够插入带有将所有字符串元素转换为字典的理解列表的数据:
cur.executemany("""INSERT INTO TABLE3_ES(Project_id,Your_Design_Score)
VALUES (%(Project_id)s, %(Your Design Score )s)""",
[ ast.literal_eval(s) for s in data3])
我有一条记录存储在data3 这是一个字符串
data3 = ['{"Project_id": "300","Your Design Score ": "N/A"}']
同时插入我的 table
cur.executemany("""INSERT INTO TABLE3_ES(Project_id,Your_Design_Score) VALUES (%(Project_id)s, %(Your Design Score )s)""", data3)
抛出错误:
TypeError: string indices must be integers, not str
我应该如何转换数据并将其加载到我的 table 中?
Oups,你的 sql executemany
需要一个可迭代的字典,而你给它一个可迭代的字符串。正确的方法是修复获取 data3 的方式,但如果不能这样做,则必须 eval 字符串来构建字典。由于 eval
是邪恶的 如果您的实际数据可以由它处理,您应该尝试使用 ast.literal_eval
。
在示例用例中,您应该能够插入带有将所有字符串元素转换为字典的理解列表的数据:
cur.executemany("""INSERT INTO TABLE3_ES(Project_id,Your_Design_Score)
VALUES (%(Project_id)s, %(Your Design Score )s)""",
[ ast.literal_eval(s) for s in data3])