Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving dictionary whose keys are tuples with json, python

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

import json
data = {(1,2,3):(a,b,c),(2,6,3):(6,3,2)}
print json.dumps(data)

Problem is I keep getting TypeError: keys must be a string.

How can I go about doing it? I tried looking at the python documentation but didn't see any clear solution. Thanks!

like image 420
Yotam Avatar asked Sep 09 '12 08:09

Yotam


1 Answers

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]}'
like image 179
Martijn Pieters Avatar answered Oct 18 '22 09:10

Martijn Pieters