Extract Python dictionary from string
<p>I have a string with valid python dictionary inside</p>

<pre><code>data = "Some string created {'Foo': u'1002803', 'Bar': 'value'} string continue etc."
</code></pre>

<p>I need to extract that dict. I tried with regex but for some reason <code>re.search(r"\{(.*?)\}", data)</code> did not work. Is there any better way extract this dict?</p>

<p>From @AChampion's suggestion.</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; import ast
&gt;&gt;&gt; x = ast.literal_eval(re.search('({.+})', data).group(0))
&gt;&gt;&gt; x
{'Bar': 'value', 'Foo': '1002803'}
</code></pre>

<p>so the pattern you're looking for is <code>re.search('({.+})', data)</code></p>

<p>You were supposed to extract the curly braces with the string, so <code>ast.literal_eval</code> can convert the string to a python dictionary . you also don't need the <code>r</code> prefix as <code>{</code> or <code>}</code> in an capturing group <code>()</code> would be matched literally.</p>

python regex django dictionary django-views