11

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!

qiao
  • 17,941
  • 6
  • 57
  • 46
Yotam
  • 9,789
  • 13
  • 47
  • 68

4 Answers4

18

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]}'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
7

If you want to load your data later on you have to postprocess it anyway. Therefore I'd just dump data.items():

>>> import json
>>> a, b, c = "abc"
>>> data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
>>> on_disk = json.dumps(data.items())
>>> on_disk
'[[[2, 6, 3], [6, 3, 2]], [[1, 2, 3], ["a", "b", "c"]]]'
>>> data_restored = dict(map(tuple, kv) for kv in json.loads(on_disk))
>>> data_restored
{(2, 6, 3): (6, 3, 2), (1, 2, 3): (u'a', u'b', u'c')}
1

You can use ujson module. ujson.dumps() accepts tuples as keys in a dictionary. You can install ujson by pip.

janok79
  • 11
  • 1
0

For Python 3* users: in addition to @Martijn Pieters answer,

dictonary.iteritems() is not valid, replace it with dictionary.items() :

json.dumps({str(k): v for k, v in data.items()})
Ofir
  • 5,049
  • 5
  • 36
  • 61