[英]How to save the dictionary that have tuple keys
我想保存在鍵上有元組的字典。
我嘗試了pickle,ujson,json來保存字典。 他們都沒有工作。
該詞典有:
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]]}
我試過了:
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())
把字典寫成字符串
with open(r'test.txt','w+') as f:
f.write(str(dictionary))
使用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
您應該使用ujson
,這適合解決您想要的問題。 我剛試過,它工作正常。 如果使用json
,則會出現以下錯誤:
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))
確保安裝了ujson
因為它不是Python標准庫的一部分:
pip install ujson
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.