sani bani
sani bani

Reputation: 83

Add values to an existing dictionary key in Python

I need to append dictionary values to an already existing JSON file. How can I be able to do that?

My details.json File

{"name": "someName"}

Dictionary generated by my python script

list1 = {"name": "someOthername"}

with open("details.json") as r:
    data = json.load(r)
    desirableDict = data.append(list1) # It has to be something like this
    print(desirableDict)

Desirable Output: {"name": ["someName", "someOthername"]}

Upvotes: 0

Views: 207

Answers (2)

JeanExtreme002
JeanExtreme002

Reputation: 231

You can check all keys within a for loop and put the values ​​of the json file and list1 inside a list like this:

import json

list1 = {"name": "someOthername"}

with open("details.json") as file:

    data = json.load(file)
    desirableDict = data.copy()

    for key in data:
        if key in list1:

            if type(data[key]) is list:
                data[key].append(list1[key])
            else:
                desirableDict[key] = [data[key],list1[key]]

print(desirableDict)

Upvotes: 1

Alexandr Shurigin
Alexandr Shurigin

Reputation: 3981

It seems like you need deep merging of structures. I would like to recommend you to use this awesome library https://pypi.org/project/deepmerge/.

There are a lot of examples like you want to achieve.

from deepmerge import always_merger

base = {"foo": ["bar"]}
next = {"foo": ["baz"]}

expected_result = {'foo': ['bar', 'baz']}
result = always_merger.merge(base, next)

assert expected_result == result

Upvotes: 1

Related Questions