Saving dictionary whose keys are tuples with json, python

前端 未结 4 2485
醉话见心
醉话见心 2021-02-20 10:37

I am writing a little program in python and I am using a dictionary whose (like the title says) keys and values are tuples. I am trying to use json as follows

im         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 10:52

    You'll need to convert your tuples to strings first:

    json.dumps({str(k): v for k, v in data.iteritems()})
    

    Of course, you'll end up with strings instead of tuples for keys:

    '{"(1, 2, 3)": ["a", "b", "c"], "(2, 6, 3)": [6, 3, 2]}'
    

提交回复
热议问题