Hakaishin Hakaishin - 1 year ago 111
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

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
I want a generic solution where I can do

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 Source

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():
            if(isinstance(value, dict)):
            assert isinstance(evaled_value,dict)

        except (SyntaxError, ValueError, AssertionError):
            #SyntaxError, ValueError are for the literal_eval exceptions
    return myDict
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download