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>The general idea referenced in my above comment is to run thru the dictionary and try and evaluate. Store that in a local variable, and then check if that evaluated expression is a dictionary. If so, then reassign it to the passed input. If not, leave it alone. </p>

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

def convert_to_dict(d):
    for key, val in d.items():
        try:
            check = ast.literal_eval(val)
        except:
            continue 
        if isinstance(check, dict):
            d[key] = check 
    return d

convert_to_dict(my_dict)
</code></pre>

python string python-3.x dictionary recursion