Jul-24-2023, 02:55 PM
(This post was last modified: Jul-24-2023, 02:55 PM by deanhystad.)
Next time try reading the documentation. Python documentation is pretty good, and I don't think it is referenced as often as it should.
https://docs.python.org/3/tutorial/datas...ctionaries
columns = list(ford)
Even if you didn't read that particular document, I'm having a tough time thinking up how you could try "various methods" and fail. Especially after you mentioned this: "I can retrieve all the dictionaries data with a for items loop.". Here are methods that use a loop to extract the dictionary keys.
You should look at using Pandas. Pandas can create a table from your dictionaries and write the table to a database.
https://docs.python.org/3/tutorial/datas...ctionaries
Quote:Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.
columns = list(ford)
Even if you didn't read that particular document, I'm having a tough time thinking up how you could try "various methods" and fail. Especially after you mentioned this: "I can retrieve all the dictionaries data with a for items loop.". Here are methods that use a loop to extract the dictionary keys.
ford = {"make": "Ford", "wheels": "4", "colour": "black"} columns = [] for item in ford.items(): columns.append(item[0]) print(columns) columns = [] for key, value in ford.items(): columns.append(key) print(columns) columns = [] for key in ford.keys(): columns.append(key) print(columns) columns = [] for key in ford: columns.append(key) print(columns) columns = [key for key in ford.keys()] columns = [key for key in ford] print(columns) columns = list(ford) print(columns)Did I misread your post?
You should look at using Pandas. Pandas can create a table from your dictionaries and write the table to a database.
import pandas as pd import sqlite3 as sql cars = [ {"make": "Ford", "wheels": "4", "colour": "black"}, {"make": "Mercedes", "wheels": "4", "colour": "white"}, {"make": "Robin", "wheels": "3", "colour": "rusty yellow"}, ] cars = pd.DataFrame(cars) print(cars.columns) conn = sql.connect("cars.db") cars.to_sql("makes", conn, if_exists="replace") conn.close