gpt4 book ai didi

python - Python 中的嵌套字典 JSON 到嵌套字典

转载 作者:行者123 更新时间:2023-11-30 22:24:18 25 4
gpt4 key购买 nike

我有一个 Python 字典字典,如下所示:

  {      
"Europe": {
"France": (10,5),
"Germany": (15,5),
"Italy": (5,15),
},
"North-America": {
"USA": (20,0),
"CANADA": (12,4),
"MEXICO": (14,8),
},
}

我想将字典保存在 JSON 文件中,以便在需要时获取数据。我这样做的商店是这样的:

with open(filename, 'a') as jsonfile:
json.dump(dictionary, jsonfile)

问题来了。当我尝试读取存储的 json 字典时,我得到同样的错误,如下所示:Python json.loads shows ValueError: Extra data

那篇文章中的答案只是将不同的字典存储在列表中并转储所有它们。但我不明白如果它们是嵌套的并且是动态创建的,该怎么做。

我读取json的方式是这样的:

jsonFile = open(filename)
data = json.loads(jsonFile)
jsonFile.close()
return data

在简历中。我需要将字典从 json 文件加载到 python 中的字典中。我怎样才能做到这一点?

最佳答案

这就是我写入 JSON 文件并从中读取的方式:

import json
from pprint import pprint

dictionary = {"Europe":
{"France": (10,5),
"Germany": (15,5),
"Italy": (5,15)},

"North-America": {
"USA": (20,0),
"CANADA": (12,4),
"MEXICO": (14,8)}
}

with open("test.json", 'w') as test:
json.dump(dictionary, test)

# Data written to test.json
with open("test.json") as test:
dictionary = json.load(test)

pprint(dictionary)

{'Europe': {'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]},
'North-America': {'CANADA': [12, 4], 'MEXICO': [14, 8], 'USA': [20, 0]}}
>>>

# Accessing dictionary["Europe"]
print(dictionary["Europe"])

{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>>

# Accessing items in dictionary["North-America"]
print(dictionary["North-America"].items())

dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>

编辑:

# Convert your input dictionary to a string using json.dumps()
data = json.dumps(dictionary)

# Write the string to a file
with open("test.json", 'w') as test:
test.write(data)

# Read it back
with open("test.json") as test:
data = test.read()

# decoding the JSON to dictionary
d = json.loads(data)

print(type(d))

<class 'dict'>
>>>

现在您可以像普通字典一样使用它:

>>> d["Europe"]
{'France': [10, 5], 'Germany': [15, 5], 'Italy': [5, 15]}
>>> d["North-America"].items()
dict_items([('USA', [20, 0]), ('CANADA', [12, 4]), ('MEXICO', [14, 8])])
>>>

关于python - Python 中的嵌套字典 JSON 到嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858802/

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