简体   繁体   English

如何使用json文件形成带有键值对的字典

[英]how to form a dictionary with key-value pair using a json file

I've this two Json files我有这两个 Json 文件

zone.json区域.json

{"0":{"id":1,"name":"XYZ"}}

region.json区域.json

{"0":{"id":1,"name":"ABC"},"1":{"id":2,"name":"DEF"}}

I need to use these json datas as values to create a dictionary with a manually entered key.我需要使用这些 json 数据作为值来创建一个带有手动输入键的字典。

{"zone": {"0":{"id":1,"name":"XYZ"}}, "region": {"0":{"id":1,"name":"ABC"},"1":{"id":2,"name":"DEF"}}}

Can anyone please explain me how to create this dictionary in Python by using the name of files as values?谁能解释我如何通过使用文件名作为值在 Python 中创建这个字典? or any other appproach?或任何其他方法?

Use json module to parse the data.使用json模块解析数据。 You can split the filename by .您可以将文件名拆分为. and use the first part as a key:并使用第一部分作为关键:

import json

file1 = 'zone.txt'
file2 = 'region.txt'

with open(file1, 'r') as f1, open(file2, 'r') as f2:
    out = {
        file1.split('.')[0]: json.load(f1),
        file2.split('.')[0]: json.load(f2)
    }

print(out)

Prints:印刷:

{'zone': {'0': {'id': 1, 'name': 'XYZ'}}, 'region': {'0': {'id': 1, 'name': 'ABC'}, '1': {'id': 2, 'name': 'DEF'}}}

Edit (to save the file):编辑(保存文件):

with open('output.txt', 'w') as f_out:
    json.dump(out, f_out)

Alternative using pathlib:使用 pathlib 的替代方法:

from pathlib import Path
import json

zonepath = Path("zone.json")
regionpath = Path("region.json")

zonedict = json.loads(zonepath.read_text())
regiondict = json.loads(regionpath.read_text())

result = {zonepath.stem: zonedict, regionpath.stem: regiondict}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM