json以元组为键序列化字典 [英] json serialize a dictionary with tuples as key

查看:80
本文介绍了json以元组为键序列化字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有一种方法可以序列化使用元组作为键的字典:

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

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

仅使用json.dumps(a)即可产生:

simply using json.dumps(a), produces:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.6/json/encoder.py", line 367, in encode
    chunks = list(self.iterencode(o))
  File "/usr/lib/python2.6/json/encoder.py", line 309, in _iterencode
    for chunk in self._iterencode_dict(o, markers):
  File "/usr/lib/python2.6/json/encoder.py", line 268, in _iterencode_dict
    raise TypeError("key {0!r} is not a string".format(key))
TypeError: key (1, 2) is not a string

推荐答案

您不能将其序列化为json,json对于什么算作dict键比python灵活得多.

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

这篇关于json以元组为键序列化字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆