Hakaishin Hakaishin - 1 month ago 8
Python Question

How to check if a string contains a dictionary

I want to recursively parse all values in a dict that are strings with

ast.literal_eval(value)
but not do that eval if the string doesn't contain a dict. I want this, because I have a string in a dict that is a dict in itself and I would like the value to be a dict. Best to give an example

my_dict = {'a': 42, 'b': "my_string", 'c': "{'d': 33, 'e': 'another string'}"}


Now I don't want a do to
ast.literal_eval(my_dict['c'])
I want a generic solution where I can do
convert_to_dict(my_dict)


I wanted to write my own method, but I don't know how to check if a string contains a dict, and then ast.literal_eval will fail, hence the question.

Answer

The other answers were really good and lead me to the right solution, but the previous accepted answer had a bug. Here is my working solution:

def recursive_dict_eval(myDict):
    for key,value in myDict.items():
        try:
            if(isinstance(value, dict)):
                recursive_dict_eval(value)
            evaled_value=ast.literal_eval(value)
            assert isinstance(evaled_value,dict)
            myDict[key]=recursive_dict_eval(evaled_value)

        except (SyntaxError, ValueError, AssertionError):
            #SyntaxError, ValueError are for the literal_eval exceptions
            pass
    return myDict