Wessi Wessi - 13 days ago 5
MySQL Question

Python dictionary stored in MySQL as Text

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

Input:

print(row.optional_items)
print(type(optional_items))


Output:

{'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
dict(row.feline_optional_items)
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

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)
Comments