【问题标题】:How to save the dictionary that have tuple keys如何保存具有元组键的字典
【发布时间】:2019-06-01 00:34:09
【问题描述】:

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

我试过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())

【问题讨论】:

  • ujson 是外部库吗?
  • 我已为您的问题添加了答案。我敢打赌你没有正确使用ujson,因为我刚试过,效果很好。

标签: python dictionary save tuples


【解决方案1】:

将字典写成字符串

 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

【讨论】:

  • 谢谢。节省工作。但是当我使用 eval 阅读时,出现了错误代码(我认为 nan 值在 key 的元素中:Traceback(最近一次调用最后一次):文件“grid_map.py”,第 101 行,在 dic = eval(dic) #这是原始字典,带有 instace 字典文件“”,第 1 行,在 NameError: name 'nan' is not defined
  • @DonggyunKim 那是你的字典有问题,只是在那个文本中使用 dic.replace('nan','"nan"') 然后使用 nan ,它会工作
  • 这是正确的代码吗?但是这段代码仍然有同样的错误。 dic = '' with open(r'depth_echo.txt','r') as f: for i in f.readlines(): dic=i dic.replace('nan', '"nan"') dic = eval (dic)
  • 这是一个在元素中包含 nan 的示例。 [-10.88394467633472,-78.22531460310272,南]
  • dic.replace('nan',0)
【解决方案2】:

您应该使用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

【讨论】:

  • 我尝试使用该代码。实际上,字典有更多的键和元素。并且出现错误代码: Traceback(最近一次调用最后一次):文件“grid_map.py”,第 97 行,在 file.write(ujson.dumps(diction)) OverflowError: 达到最大递归级别
  • @DonggyunKim,这很奇怪,我完全按照您提供的示例运行代码,并且运行正常,文件中有以下内容:{"(1, 2, 3)":["a","b","c"],"(2, 6, 3)":[6,3,2]}%
猜你喜欢
  • 2012-09-02
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多