I have generated a very large dictionary after processing an XML file, and I am looking extract from this dictionary and to insert columns and values into my mySQL database table.
I am using Python 3.
The dictionary is nested; here's a simplistic example of what I have:
d ={'Test1'{'TestID':'first','Dev_Type':'this device','Version':'v1_0','Address':'some Address'}
'Test2'{'TestID':'second','Dev_Type':'that device','Version':'v1_0','Address':'other Address'}
'Test3'{'TestID','third','Dev_Type':'other device','Version':'v1_0','Address':'another Address'}
}
Essentially I want to iterate over each primary Key in this dictionary (e.g. Test1,Test2,Test3) and extract the secondary keys as a column name tuple and the associated seconday key values as a values tuple, a bit like this:
cols = ('TestID','Dev_Type','Version','Address')
vals = ('first','this device','v1_0','some Address')
On iterating over each primary key I will add the two tuples to my mySQL table using this command:
sql = "INSERT INTO Parameters ({0}) VALUES ({1})".format(', '.join(cols), ', '.join(['%s'] * len(cols)));
try:
cursor.execute(sql, vals)
except Exception as e:
print(e)
pass
Then repeat the process on the next primary key ('Test2').
I have made an initial attempt, but have hard coded the Primary key in this instance:
for k, v in d:
#Missing appropriate method here
cols = tuple(d['Test1'].keys())
vals = tuple(d['Test1'].values())
sql = "INSERT INTO Parameters ({0}) VALUES ({1})".format(', '.join(cols), ', '.join(['%s'] * len(cols)));
try:
cursor.execute(sql, vals)
except Exception as e:
pass
connection.close()
return
:between the keys and values in your example dict?