如何保存具有元组键的字典 [英] How to save the dictionary that have tuple keys

查看:70
本文介绍了如何保存具有元组键的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存在键上有元组的字典。

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

我尝试了pickle,ujson,json来保存字典。所有人都没有用。

I tried pickle, ujson, json to save the dictionary. All of them did not work.

字典有:

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

read使用 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

这篇关于如何保存具有元组键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆