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

Cod*_*Lvl 3 python json dictionary

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

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

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

with open(filename, 'a') as jsonfile:
    json.dump(dictionary, jsonfile)
Run Code Online (Sandbox Code Playgroud)

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

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

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

jsonFile = open(filename)
data = json.loads(jsonFile)
jsonFile.close()
return data
Run Code Online (Sandbox Code Playgroud)

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

Sri*_*ila 6

这就是我写入 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])])
>>>
Run Code Online (Sandbox Code Playgroud)

编辑

# 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'>
>>> 
Run Code Online (Sandbox Code Playgroud)

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

>>> 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])])
>>>
Run Code Online (Sandbox Code Playgroud)