astroboy
astroboy

Reputation: 197

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

I've this two Json files

zone.json

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

region.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.

{"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? or any other appproach?

Upvotes: 0

Views: 323

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195573

Use json module to parse the data. 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)

Upvotes: 3

Wups
Wups

Reputation: 2569

Alternative using 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}

Upvotes: 1

Related Questions