本文介绍了使用json,python保存键为元组的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用python写一个小程序,我使用的字典(如标题所示)的键和值是元组.我正在尝试按以下方式使用json
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)
问题是我一直在获取TypeError: keys must be a string
.
我该如何去做?我尝试查看python文档,但未找到任何明确的解决方案.谢谢!
How can I go about doing it? I tried looking at the python documentation but didn't see any clear solution. Thanks!
推荐答案
您需要先将元组转换为字符串:
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]}'
这篇关于使用json,python保存键为元组的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!