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

时间:2017-12-17 19:45:06

标签: 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),
       },
 }

我想将字典保存在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中的字典。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分: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])])
>>>