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])])

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值