gpt4 book ai didi

python - 如何将复杂的字典保存在 JSON 文件中,然后将其作为字典加载回来?

转载 作者:行者123 更新时间:2023-12-01 04:47:56 27 4
gpt4 key购买 nike

我不确定我是否正确;我正在尝试在 python 中使用 json 库。

我将嵌套字典转储到磁盘上的 json 文件中,然后我想像以前一样将其加载回来。尽管当我加载回文件时,我没有得到与之前相同的对象。

mydictionary=defaultdict(dict)
...
with open("myfile.json", "w") as outfile:
dump(mydictionary, outfile) #saving the dictionary to json file
....
with open("myfile.json") as outfile:
restored_dict=load(outfile)
for keys in restored_dict:
print keys

字典结构:

{
"product1": {
"item1" : [
"red",
"soft",
"430"
],
"item2" : [
"green",
"soft",
"112"
],
"item3" : [
"blue",
"hard",
"12"
]
},
"product2": {
"item4" : [
"black",
"soft",
"30"
],
"item5" : [
"indigo",
"hard",
"40"
],
"item6" : [
"green",
"soft",
"112"
]
}
}

当我打印前后的对象时,它们不一样;恢复字典后,我无法再访问键和值。我得到一长串数据,每个项目和键的开头都有一个“u”;正确打印它的唯一方法是再次转储它并打印输出

print dumps(restored_dict, indent=4)

但我仍然无法访问键、值和项目。

我看到有 2 个函数:一个函数末尾有 s(dump-dumps、load-loads),但我无法区分。网上一些教程说带有 s 的是创建一个字符串而不是 json 对象,而另一些教程则说一个以二进制保存,另一个以纯文本保存......

我正在尝试保存字典,并在稍后加载它;我认为 json 是实现此目的的最简单方法,但由于某种原因我无法实现此目的。

最佳答案

JSON 以 Unicode 格式存储数据。 u 前缀表明您在加载 Python 时也有 Unicode 字符串。

如果您的键仅包含 ASCII 字符,则可以使用字节字符串加载这些键(省略 u 前缀):

>>> import json
>>> d = {'foo': 'bar'}
>>> new_d = json.loads(json.dumps(d))
>>> new_d
{u'foo': u'bar'}
>>> new_d['foo']
u'bar'

如果您的 key 是 UTF-8 编码的,则必须将它们解码为 Unicode 字符串,或使用 Unicode 字符串文字(再次以 u 字符作为前缀):

>>> utf8_key = u'å'.encode('utf8')  # manually encoded for demo purposes
>>> utf8_key
'\xc3\xa5'
>>> utf8_d = {utf8_key: 'bar'}
>>> utf8_d
{'\xc3\xa5': 'bar'}
>>> new_utf8_d = json.loads(json.dumps(utf8_d))
>>> new_utf8_d
{u'\xe5': u'bar'}
>>> new_utf8_d[u'å']
u'bar'

字符串值仍然是 Unicode 字符串;如果需要字节,您可以将它们编码回 UTF-8,但一般来说最好尽可能将文本处理为 Unicode。

打印 Unicode 字符串会自动将它们编码为当前 stdout 目标的正确编解码器。

您可能想阅读有关 Python 和 Unicode 的内容:

或者,使用 pickle library为您提供往返 Python 数据格式。然而,输出不会像 JSON 那样是人类可读的。

关于python - 如何将复杂的字典保存在 JSON 文件中,然后将其作为字典加载回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29027549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com