Search code examples
pythondictionaryeval

Convert a string representation of a set of tuples to a dictionary


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}

Solution

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