Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, store a dict in a database

What's the best way to store and retrieve a python dict in a database?

like image 491
ensnare Avatar asked May 20 '10 20:05

ensnare


People also ask

Can we store dictionary in MySQL?

Storing all dictionary information in InnoDB tablesThe MySQL 8.0. 0 now stores dictionary data in InnoDB tables.

How do you store a dictionary?

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.

Can you store a dictionary in a database?

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.


1 Answers

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"}))
like image 98
catchmeifyoutry Avatar answered Sep 21 '22 19:09

catchmeifyoutry