Wessi Wessi - 1 year ago 71
MySQL Question

Python dictionary stored in MySQL as Text

I have a column in a MySQL Database where Python dictionaries are stored as text.




{'Barneseng kr. 90,-': '90,00', 'Baby Badekar': '90,00', 'Barnestol': '90,00', 'Tilbagetrædelsesgebyr': '150,00', 'Slutrengøring (afrejse kl. 9.00)'
: '730,00', 'Linnedpakke (inkl. håndklæde og viskestykke) Kr. 90,-': '90,00'}
<class 'str'>

I would like to work with the variable as a Python dictionary but it is not possible because Python considers it a string. I've tried converting it to a dict by using
but it returns
ValueError: dictionary update sequence element #0 has length 1; 2 is required

Is there a way to convert row.optional_items to a dictionary so I can work with it?

I hope someone can help. Thanks!

Answer Source

If you want to convert a dict in string form to an actual dict, do this:

from ast import literal_eval
dict_str = "{'a': 1}"
dict_dict = literal_eval(dict_str)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download