Skip to content Skip to sidebar Skip to footer

Insert Dictionary Within List To Database In Python

I have a list as below,I have trimmed the list.The data is by date.So for each date there are values for different items. each index of the list is a dictionary ls=[{'item1': 6755,

Solution 1:

You have three tasks:

  1. Exclude the date fields from the list
  2. Set up Python to run SQL commands
  3. Create code to insert the data into the database

I'm not 100% sure how you hope to store the data that you've included in the database, but I'll give my best guess.

items_to_insert = []
for dictionary in ls:
  #pop removes the value from the dict
  date_for_insert = dictionary.pop("datetime", None)
  if date_for_insert isNone:
    raise ValueError('No datetime - aborting')
  for key in dictionary:
    items_to_insert.append([date_for_insert, key, dictionary[key]

This code goes to each dictionary in the ls list, removes the datetime, and then parses the data into an array. Now you're set to insert the data

For task 2 you'll need to use PyMySQL or something like it, and set up your connections and stuff, and then for task 3 run:

for item in items_to_insert:
  cursor.execute("INSERT INTO mytable (Datetime,Item,Value) VALUES ('{}', '{}', '{}')".format(item[0], item[1], item[2]))

Or something like that. This line is easier because of the data preprocessing from above.

You may need to format the datetime in a certain way for this code to work correctly.

Post a Comment for "Insert Dictionary Within List To Database In Python"