How to check if a string contains a dictionary
<p>I want to recursively parse all values in a dict that are strings with <code>ast.literal_eval(value)</code> 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</p>

<pre><code>my_dict = {'a': 42, 'b': "my_string", 'c': "{'d': 33, 'e': 'another string'}"}
</code></pre>

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

<p>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.</p>

<p>Here is a proposition that handles recursion. As it was suggested in the comments, it tries to eval everything then check if the result is a dict, if it is we recurse, else we skip the value . I sligthly altered the initial dict to show that it hanldes recusion fine :</p>

<pre><code>import ast
my_dict = {'a': 42, 'b': "my_string", 'c': "{'d': 33, 'e': \"{'f' : 64}\"}"}

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

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

print(my_dict)
print(recursive_dict_eval(my_dict))
</code></pre>

<p>Output:</p>

<pre><code>{'a': 42, 'b': 'my_string', 'c': '{\'d\': 33, \'e\': "{\'f\' : 64}"}'}
{'a': 42, 'b': 'my_string', 'c': {'e': {'f': 64}, 'd': 33}}
</code></pre>

python string python-3.x dictionary recursion