-5

I have a long string representing a set of tuples:

my_string = '{(76034,0),(91316,0),(221981,768),(459889,0),(646088,0)}'

How can I convert it to the following dict?

expected_result = {76034: 0, 91316: 0, 221981: 768, 459889: 0, 646088: 0}
Georgy
  • 12,464
  • 7
  • 65
  • 73
ERJAN
  • 23,696
  • 23
  • 72
  • 146

3 Answers3

2

If you do literal_eval on that string, it returns a set. But if you'd like a dict, you can convert it to one using dict():

In [1]: from ast import literal_eval

In [2]: s = '{(76034,0),(91316,0),(221981,768),(459889,0),(646088,0)}'

In [3]: literal_eval(s)
Out[3]: {(76034, 0), (91316, 0), (221981, 768), (459889, 0), (646088, 0)}

In [4]: conv_s = literal_eval(s)

In [5]: dict(conv_s)
Out[5]: {459889: 0, 646088: 0, 221981: 768, 91316: 0, 76034: 0}
amanb
  • 5,276
  • 3
  • 19
  • 38
1

You can convert string to its corresponding datatype in python using eval.

>>> a = '{(76034,0),(91316,0),(221981,768),(459889,0),(646088,0)}'
>>> eval(a)
set([(76034, 0), (459889, 0), (646088, 0), (221981, 768), (91316, 0)])
>>> 

What you have posted is a set data structure.

Or since eval is indeed risky to use, you should use ast.literal_eval as in other answer. Also see this answer: [Using python's eval() vs. ast.literal_eval()?

So that now the code becomes:

>>> import ast
>>> ast.literal_eval(a[1:-1])
((76034, 0), (91316, 0), (221981, 768), (459889, 0), (646088, 0))
>>> 
thelogicalkoan
  • 620
  • 1
  • 5
  • 13
-3

Try using ast.literal_eval:

import ast
s = '{(76034,0),(91316,0),(221981,768),(459889,0),(646088,0)}'
print(dict(ast.literal_eval('[' + s.strip('{}') + ']')))

Output:

{76034: 0, 91316: 0, 221981: 768, 459889: 0, 646088: 0}
U13-Forward
  • 69,221
  • 14
  • 89
  • 114