json serialize a dictionary with tuples as key

前端 未结 6 1875
走了就别回头了
走了就别回头了 2020-12-05 09:27

Is there a way in Python to serialize a dictionary that is using a tuple as key:

a={(1,2):\'a\'}

simply using json.dumps(a), produces:

6条回答
  •  清歌不尽
    2020-12-05 10:05

    You can't serialize that as json, json has a much less flexible idea about what counts as a dict key than python.

    You could transform the mapping into a sequence of key, value pairs, something like this:

    >>> import json
    >>> def remap_keys(mapping):
    ...     return [{'key':k, 'value': v} for k, v in mapping.iteritems()]
    ... 
    >>> json.dumps(remap_keys({(1, 2): 'foo'}))
    '[{"value": "foo", "key": [1, 2]}]'
    

提交回复
热议问题