简体   繁体   English

如何保存具有元组键的字典

[英]How to save the dictionary that have tuple keys

I would like to save the dictionary having tuple on keys. 我想保存在键上有元组的字典。

I tried pickle, ujson, json to save the dictionary. 我尝试了pickle,ujson,json来保存字典。 All of them did not work. 他们都没有工作。

The dictionary has: 该词典有:

dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

I tried: 我试过了:

with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

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())

write the dictionary as string 把字典写成字符串

 with open(r'test.txt','w+') as f:
     f.write(str(dictionary))

read using eval 使用eval读取

dic = ''
with open(r'test.txt','r') as f:
         for i in f.readlines():
            dic=i #string
dic = eval(dic) # this is orignal dict with instace dict

You should use ujson , this is appropriate to address what you want. 您应该使用ujson ,这适合解决您想要的问题。 I just tried it and it works properly. 我刚试过,它工作正常。 If you use json you will get the following error: 如果使用json ,则会出现以下错误:

TypeError: keys must be str, int, float, bool or None, not tuple TypeError:键必须为str,int,float,bool或None,而不是元组

import ujson

d = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

# save dictionary
with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(d))

Make sure you installed ujson since it is not part of the Python standard library: 确保安装了ujson因为它不是Python标准库的一部分:

pip install ujson

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM