0

I have a record which is stored in data3 which is a string

data3 = ['{"Project_id": "300","Your Design Score ": "N/A"}']

while inserting into my table

cur.executemany("""INSERT INTO TABLE3_ES(Project_id,Your_Design_Score) VALUES (%(Project_id)s, %(Your Design Score )s)""", data3)

It is throwing error:

TypeError: string indices must be integers, not str

How should I convert and load the data into my table?

halfer
  • 19,824
  • 17
  • 99
  • 186
venkat
  • 1,203
  • 3
  • 16
  • 37

1 Answers1

1

Oups, your sql executemany expects an iterable of dictionaries, and you give it an iterable of strings. The correct way would be to fix the way you get data3, but if you cannot do that, you must eval the strings to build a dicts. As eval is evil you should try to use ast.literal_eval if your actual data can be processed by it.

In the example use case, you should be able to insert the data with a comprehension list converting all string elements to dictionaries:

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])
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Alternatively, if the data is supposed to be legal JSON, `json.loads` would also work (and is generally faster to boot). – ShadowRanger Dec 31 '17 at 16:37