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}
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}
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}
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))
>>>
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}