How to save the dictionary that have tuple keys

萝らか妹 提交于 2020-06-27 17:17:28

问题


I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. 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())

回答1:


write the dictionary as string

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

read using 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



回答2:


You should use ujson, this is appropriate to address what you want. I just tried it and it works properly. If you use json you will get the following error:

TypeError: keys must be str, int, float, bool or None, not tuple

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:

pip install ujson


来源:https://stackoverflow.com/questions/56403013/how-to-save-the-dictionary-that-have-tuple-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!