JSON 序列化以元组为键的字典
Python 有没有办法序列化使用元组作为键的字典?
例如,
a = {(1, 2): 'a'}
仅使用 json.dumps(a) 会引发此错误:
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
Is there a way in Python to serialize a dictionary that is using a tuple as key?
e.g.
a = {(1, 2): 'a'}
simply using json.dumps(a)
raises this error:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
你不能将其序列化为 json,与 python 相比,json 关于什么算作 dict 键的灵活性要低得多。
您可以将映射转换为一系列键、值对,如下所示:
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:
请参阅https://stackoverflow.com/a/12337657/2455413。
See https://stackoverflow.com/a/12337657/2455413.
您可以只使用
str((1,2))
作为键,因为 json 仅期望键作为字符串,但如果您使用它,则必须使用a[str((1, 2))]
获取值。You could just use
str((1,2))
as key because json only expects the keys as strings but if you use this you'll have to usea[str((1,2))]
to get the value.JSON 仅支持字符串作为键。您需要选择一种将这些元组表示为字符串的方法。
JSON only supports strings as keys. You'll need to choose a way to represent those tuples as strings.
该解决方案:
eval()
的安全风险。\"
,这比这里的其他str()
/eval()
方法更糟糕。This solution:
eval()
.\"
to the tuple representation, which is worse than the otherstr()
/eval()
methods here.json 只能接受字符串作为 dict 的键,
你可以做的就是用字符串替换元组键,就像这样
当你想读取它时,你可以使用将键更改回元组
json can only accept strings as keys for dict,
what you can do, is to replace the tuple keys with string like so
And than when you want to read it, you can change the keys back to tuples using
这是一种方法。它将要求在主字典解码和整个字典重新排序后对密钥进行 json 解码,但它是可行的:
我不声明此方法有任何效率。我需要这个来将一些操纵杆映射数据保存到文件中。我想使用一些可以创建半人类可读格式的东西,以便在需要时可以对其进行编辑。
Here is one way to do it. It will require the key to be json decoded after the main dictionary is decoded and the whole dictionary re-sequenced, but it is doable:
I make no claim to any efficiency of this method. I needed this for saving some joystick mapping data to a file. I wanted to use something that would create a semi-human readable format so it could be edited if needed.
您可以使用以下两个函数将 dict_having_tuple_as_key 转换为 json_array_having_key_and_value_as_keys,然后按照
使用示例的方式将其反转换:
(使用@SingleNegationElimination表达的概念来回答@Kvothe评论)
Here are two functions you could use to convert a dict_having_tuple_as_key into a json_array_having_key_and_value_as_keys and then de-convert it the way back
usage example:
(Using concepts expressed by @SingleNegationElimination to answer @Kvothe comment)
实际上,您不能将元组序列化为 json 的键,但可以在反序列化文件后将元组转换为字符串并恢复它。
但是不能用json序列化。但是,您可以使用
一点作弊,您将通过单独处理每个键(作为 str)来恢复原始元组(在反序列化整个文件之后)
使用
json.loads
,但它会起作用。将其封装起来就完成了。平静下来,快乐编码!
尼古拉斯
You can actually not serialize tuples as key to json, but you can convert the tuple to a string and recover it, after you have deserialized the file.
But you cannot serialize it with json. However, you can use
With a bit of cheating, you will recover the original tuple (after having deserialized the whole file) by treating each key (as str) separately
It is a bit of overload to convert a string to a tuple using
json.loads
, but it will work. Encapsulate it and you are done.Peace out and happy coding!
Nicolas
下面是一个完整的示例,用于将带有元组键和值的嵌套字典编码到 json 中/从 json 中解码。元组键将是 JSON 中的字符串。
tuple 或 set 类型的值将转换为列表
用法
Here's a complete example to encode/decode nested dictionaries with tuple keys and values into/from json. tuple key will be a string in JSON.
values of types tuple or set will be converted to list
usage
其实还有更简单的方法,不过需要修改原来的字典。
这个想法是要进入一种不同的心态。使用元组作为键与嵌套字典相同,您可以在嵌套字典中进行两次查找。具体来说,它在功能上相当于将字典转换为
这可以直接 jasonified,无需任何特殊处理或使用
eval
。There’s actually a simpler way, though it requires changing the original dictionary.
The idea is to get into a different mindset. Using a tuple as key is the same as a nested dictionary where you do two lookups instead. Specifically, it’s functionally equivalent to transform the dictionary to
This can be directly jasonified without any special treatment or the usage of
eval
.