天天看點

python字典嵌套字典_嵌套字典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])])

>>>

編輯:

^{pr2}$

現在你可以像普通字典一樣使用它:>>> 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])])

>>>