Saving dictionary whose keys are tuples with json, python

别来无恙 提交于 2019-12-04 03:24:09

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]}'

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

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

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()})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!