What's the best way to store and retrieve a python dict in a database?
Storing all dictionary information in InnoDB tablesThe MySQL 8.0. 0 now stores dictionary data in InnoDB tables.
Saving Dictionary to a File This method would include the following steps: Opening a file in write/append text mode. Converting the dictionary into a string. Entering the converted string into the file using write function.
If you really want to store the full dictionary as a single string, then you could serialize your dictionary to JSON (or XML) and store the result to the database.
If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example MongoDB. The MongoDB python bindings allow you to just insert dicts in the DB, and query them based on the values in the dict. See for example the code below:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["mydatabase"]
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
And to find the entry:
print(mycol.find_one({"name":"John"}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With