0

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?

2
  • Do you "Trust" the string? If it is generated from user input, then it is not trusted. It matters since it may be possible to use eval if the string is trusted. Commented Sep 16, 2016 at 16:50
  • Thanks for the reply. @James K I have edited my question a bit. Commented Sep 16, 2016 at 18:17

1 Answer 1

3

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')]}
Sign up to request clarification or add additional context in comments.

4 Comments

Was going to post the identical solution but realized that it would break for { a: [(b, c, something else)] }. Not sure if that's an issue or not.
@JustinNiessner good point, the solution is not that reliable at this point and can break in many different ways, but I hope this is something the OP can start with (or stop, if realized the complexity of the problem :))..interesting to know where is this coming from..thanks!
Thank you for the quick reply, guys!
@alecxe . I have edited my question a bit. Added my real scenario. Thanks for the help, guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.