beenum
beenum

Reputation: 31

String split into dictionary containing lists in python

I have to split a string that looks like;

'{ a:[(b,c), (d,e)] , b: [(a,c), (c,d)]}'

and convert it to a dict whose values are a list containing tuples like;

{'a':[('b','c'), ('d','e')] , 'b': [('a','c'), ('c','d')]}

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

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

I want it to be just like it was at the server side.

{'write_times': [ ('1.65893554687', '1474049078179.095'), ('1.998779296875', '1474049078181.098')],  'read_times': [('0.825927734375', '1474049447696.7249'), ('1.4638671875', '1474049447696.7249')]}

The solution you proposed may not work. Any ideas?

Upvotes: 0

Views: 64

Answers (1)

alecxe
alecxe

Reputation: 473873

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 ast.literal_eval() to safely eval it:

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

Upvotes: 3

Related Questions