String split into dictionary containing lists in python
<p>I have to split a string that looks like;</p>

<pre><code>'{ a:[(b,c), (d,e)] , b: [(a,c), (c,d)]}'
</code></pre>

<p>and convert it to a dict whose values are a list containing tuples like;</p>

<pre><code>{'a':[('b','c'), ('d','e')] , 'b': [('a','c'), ('c','d')]}
</code></pre>

<p>In my case;
The above string was just an example. So what I am trying to do actually is that I'm getting a response from server. At server side, the response is proper dictionary with lists and stuff. But it sends to my client in a string format somehow. for example</p>

<pre><code>u"{'write_times': [ (1.658935546875, 1474049078179.095), (1.998779296875, 1474049078181.098)],  'read_times': [(0.825927734375, 1474049447696.7249), (1.4638671875, 1474049447696.7249)]}"
</code></pre>

<p>I want it to be just like it was at the server side.</p>

<pre><code>{'write_times': [ ('1.65893554687', '1474049078179.095'), ('1.998779296875', '1474049078181.098')],  'read_times': [('0.825927734375', '1474049447696.7249'), ('1.4638671875', '1474049447696.7249')]}
</code></pre>

<p>The solution you proposed may not work. Any ideas?</p>

<p>It is important to know where this string is coming from, but, assuming this is what you have and you cannot change that, you can pre-process the string putting alphanumerics into quotes and using <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a> to <em>safely</em> eval it:</p>

<pre><code>&gt;&gt;&gt; from ast import literal_eval
&gt;&gt;&gt; import re
&gt;&gt;&gt;
&gt;&gt;&gt; s = '{ a:[(b,c), (d,e)] , b: [(a,c), (c,d)]}'
&gt;&gt;&gt; literal_eval(re.sub(r"(\w+)", r"'\1'", s))
{'a': [('b', 'c'), ('d', 'e')], 'b': [('a', 'c'), ('c', 'd')]}
</code></pre>

python split