IIUC you need to join two dicts into one, you could do it with update:

a = {"cars": 1, "houses": 2, "schools": 3, "stores": 4}
b = {"Pens": 1, "Pencils": 2, "Paper": 3}

a.update(b)
print(a)

output would looks like:

{'Paper': 3, 'cars': 1, 'Pens': 1, 'stores': 4, 'Pencils': 2, 'schools': 3, 'houses': 2}

To create whole new dict without touching a you could do:

out = dict(list(a.items()) + list(b.items()))

print(out)
{'Paper': 3, 'cars': 1, 'Pens': 1, 'stores': 4, 'Pencils': 2, 'schools': 3, 'houses': 2}

EDIT

For your case you could load your json with json.load update it and then save it with json.dump:

mydict = {"Pens": 1, "Pencils": 2, "Paper": 3}
with open('myfile.json' , 'r+') as f:
   d = json.load(f)
   d.update(mydict)
   f.seek(0)
   json.dump(d, f)
   
Answer from Anton Protopopov on Stack Overflow
🌐
PyPI
pypi.org › project › jsonmerge
jsonmerge · PyPI
Any properties that are present both in base and head are merged based on the strategy specified further down in the hierarchy (e.g. in properties, patternProperties or additionalProperties schema keywords). The objClass option allows one to request a different dictionary class to be used to hold the JSON object. The possible values are names that correspond to specific Python classes.
      » pip install jsonmerge
    
Published   Jul 19, 2023
Version   1.9.2
Discussions

How to merge two json string in Python? - Stack Overflow
I recently started working with Python and I am trying to concatenate one of my JSON String with existing JSON String. I am also working with Zookeeper so I get the existing json string from zookee... More on stackoverflow.com
🌐 stackoverflow.com
What is the best way to merge two JSON file in Python?
You'll need to give a bit more information, ideally examples of the two docs and what you want the output to be. More on reddit.com
🌐 r/learnpython
8
5
May 2, 2024
Merge two json object in python - Stack Overflow
the solution is to convert both ... the two dictionaries together on a key · ListenSoftware Louise Ai Agent – ListenSoftware Louise Ai Agent · 2021-03-02 23:35:28 +00:00 Commented Mar 2, 2021 at 23:35 ... In json module, dumps convert python object to a string, and loads convert a string into python object. So in your original codes, you just try to concat two json-string. Try to code like this: import json from collections import defaultdict def merge_dict(d1, d2): ... More on stackoverflow.com
🌐 stackoverflow.com
May 2, 2021
is it possible merge two json object
some function like this json1.join(json2) or json1.merge(json2) or json1 += json2 More on github.com
🌐 github.com
14
January 15, 2017
🌐
AskPython
askpython.com › home › what is json and how to merge two json strings?
What Is JSON and How To Merge Two Json Strings? - AskPython
March 16, 2023 - These two dictionaries are merged using the merge method of the jsonmerge library.
Top answer
1 of 6
45

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

EDIT 2 Nov 2024: Pretty sure we can now do merged = dictA | dictB

2 of 6
39

Assuming a and b are the dictionaries you want to merge:

c = {key: value for (key, value) in (a.items() + b.items())}

To convert your string to python dictionary you use the following:

import json
my_dict = json.loads(json_str)

Update: full code using strings:

# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)

# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)

merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}

# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)

But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.


Alternative solution:

jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)

new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)

errors_dict[new_error_key] = new_error_str

# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))

And actually you can avoid all these if you just use an array to hold all your errors.

🌐
Reddit
reddit.com › r/learnpython › what is the best way to merge two json file in python?
r/learnpython on Reddit: What is the best way to merge two JSON file in Python?
May 2, 2024 -

Hello everyone,

I am trying to merge two JSON files, but I couldn't find any quick package that can do this. One file contains the base policy, while the other includes additional files for excluding special configurations.

My goal is to merge these two JSON files of AntiVirus policy, which contain arrays and numerous elements, without overwriting any data. I was wondering what the best approach would be to accomplish this.

If its element just uses the value of the other files.
If its array just append new elements.

What is best way to achieve this goal?

Thanks all

🌐
Bobby Hadz
bobbyhadz.com › blog › merge-two-json-objects-in-python
How to merge two JSON objects in Python [5 Ways] | bobbyhadz
April 11, 2024 - ... Copied!import json obj1 = ....loads(obj1))) # 👉️ <class 'dict'> The last step is to use the dictionary unpacking ** operator to merge the two dictionaries....
🌐
datagy
datagy.io › home › python posts › python merge dictionaries – combine dictionaries (7 ways)
Python Merge Dictionaries - Combine Dictionaries (7 Ways) • datagy
September 28, 2024 - Python introduced a new way to merge dictionaries in Python 3.9, by using the merge operator |. Merging two dictionaries with the merge operator is likely the fastest and cleanest way to merge two dictionaries.
🌐
CopyProgramming
copyprogramming.com › howto › how-to-merge-two-json-string-in-python
Python: Combining Two JSON Strings in Python: A Guide
April 21, 2023 - The json module provides two methods for converting Python objects to strings and strings to Python objects. Therefore, instead of simply concatenating two json-string in your original code, try coding in the following manner: import json from collections import defaultdict def merge_dict(d1, d2): dd = defaultdict(list) for d in (d1, d2): for key, value in d.items(): if isinstance(value, list): dd[key].extend(value) else: dd[key].append(value) return dict(dd) if __name__ == '__main__': json_str1 = json.dumps({"a": [1, 2]}) json_str2 = json.dumps({"a": [3, 4]}) dct1 = json.loads(json_str1) dct2 = json.loads(json_str2) combined_dct = merge_dict(dct1, dct2) json_str3 = json.dumps(combined_dct) # {"a": [1, 2, 3, 4]} print(json_str3)
Find elsewhere
🌐
GitHub
gist.github.com › evansd › cf68c203aa1a9a9eb78aff1e38de5c92
Merge nested JSON dictionaries · GitHub
Merge nested JSON dictionaries · Raw · mege_json.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
YouTube
youtube.com › watch
Merging Two JSON Dictionaries in Python - YouTube
Learn how to effectively merge two JSON dictionaries in Python with this easy-to-follow guide. Understand the mechanics behind merging nested structures seam...
Published   March 27, 2025
Views   0
🌐
GitHub
github.com › nlohmann › json › issues › 428
is it possible merge two json object · Issue #428 · nlohmann/json
January 15, 2017 - some function like this json1.join(json2) or json1.merge(json2) or json1 += json2
Author   itviewer
🌐
Medium
medium.com › @programinbasic › merge-multiple-json-files-into-one-in-python-65c009aad81d
Merge Multiple JSON files into One in Python | by ProgrammingBasic | Medium
January 17, 2024 - So this is how you can merge JSON files into one single file using Pythons’s built-in json modules or using Pandas library.
🌐
pytz
pythonhosted.org › json-merger › _modules › json_merger › merger.html
json_merger.merger — json-merger 0.2.2 documentation
""" def __init__(self, root, head, update, default_dict_merge_op, default_list_merge_op, list_dict_ops=None, list_merge_ops=None, comparators=None, data_lists=None): """ Args: root: A common ancestor of the two objects being merged. head: One of the objects that is being merged. Refers to the version that is currently in use. (e.g. a displayed database record) update: The second object that is being merged. Refers to an update that needs to be integrated with the in-use version. default_dict_merge_op (:class:`json_merger.config.DictMergerOps` class attribute): Default strategy for merging regular non list JSON values (strings, numbers, other objects).
Top answer
1 of 2
2
dict1 = {"CA": [{"Marin": [{"zip":1}], "population":10000}]}
dict2 = {"CA": {"Marin": {"zip":2}}}

Looking at dict2:

  • You are given dict2, containing key k (in this case k = "CA")
  • dict2[k] itself is a dictionary, that contains one (or more) key (c = "Marin") - value (z) pair(s)
  • z now is the dictionary that you care about.

Looking at dict1:

  • For each element county_info in dict1[k], you care about the one that has a key c.
  • The value at this key (county_info[c]) is a list, to which you want to append z

So let's do that:

def merge_lines(dict1, dict2):
    for k, v in dict2.items():
        for c, z in v.items():
            # Find the element of dict1[k] that has the key c:
            for county_info in dict1[k]:
                if c in county_info:
                    county_info[c].append(z)
                    break

Since the function modifies dict1 in-place, running merge_lines(dict1, dict2) gives us a modified dict1 that looks like what you expect:

{'CA': [{'Marin': [{'zip': 1}, {'zip': 2}], 'population': 10000}]}
2 of 2
0

This is a more generic approach, where d1 is updated with changes contained in d2. Of course, you should provide more examples of updates from d2 to see if my solution works in all cases.

#!/usr/bin/env python3

d1 = {"CA": [{"Marin": [{"zip": 1}], "population": 10000}]}
d2 = {"CA": {"Marin": {"zip": 2}}}


# read update data from d2 and append new values to d1
def update(d1, d2):
    for key, value in d2.items():
        if key in d1:
            for key1, value1 in value.items():
                if key1 in d1[key][0]:
                    d1[key][0][key1].append(value1)
                else:
                    d1[key][0][key1] = [value1]
        else:
            d1[key] = [value]

    return d1


print(update(d1, d2))
🌐
Programmingbasic
programmingbasic.com › merge-multiple-json-objects-into-one-single-object-python
Merge multiple JSON objects into one single object in Python
March 27, 2025 - Combine multiple JSON objects from a file into a single object and then save it in a file in python.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
April 28, 2025 - In this example, the merge_json_files function reads and merges JSON files from the specified directory ("./files"). The combined data is then written to a new JSON file named "merged.json," and the merged data is printed for confirmation.
🌐
Stack Abuse
stackabuse.com › how-to-merge-two-dictionaries-in-python
How to Merge Two Dictionaries in Python
August 31, 2023 - Merges usually happen from the right to left, as dict_a <- dict_b. When there's a common key holder in both the dictionaries, the second dictionary's value overwrites the first dictionary's value. This can be demonstrated in the illustration given below, where the components of the dictionary ...