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

问题描述 投票:1回答:1

我在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

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

我读json的方式是这样的:

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

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

python json dictionary
1个回答
2
投票

这是我写入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])])
>>>
© www.soinside.com 2019 - 2024. All rights reserved.