-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
  • 9,972
  • 7
  • 57
  • 66
ERJAN
  • 22,540
  • 20
  • 65
  • 127

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
  • 4,641
  • 2
  • 17
  • 36
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
  • 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}
U12-Forward
  • 65,118
  • 12
  • 70
  • 89