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 OverflowIIUC 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)
To add onto what Anton said, you can read the json file into a dictionary. Afterwards use a.update(b) like he has, and overwrite the file.
If you open the file to append, and do json dump like you have it will just create another line with the new json data.
Hope this helps.
» pip install jsonmerge
How to merge two json string in Python? - Stack Overflow
What is the best way to merge two JSON file in Python?
Merge two json object in python - Stack Overflow
is it possible merge two json object
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
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.
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
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):
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)
json.dumps() converts a dictionary to str object, not a json(dict) object.
So, adding some dumps statement in your code shows that the type is changed to str after using json.dumps() and with + you are effectively concatenating the two string and hence you get the concatenated output.
Further, to merge the two dictionaries for your simple case, you can just use the append:
import json
json_obj = json.dumps({"a": [1,2]})
json_obj1 = json.dumps({"a": [3,4]})
print(type(json_obj1)) # the type is `str`
json_obj += json_obj1 # this concatenates the two str objects
json_obj = {"a": [1,2]}
json_obj1 = {"a": [3,4]}
json_obj["a"].extend(json_obj1["a"])
print(json_obj)
dict1 = {"CA": [{"Marin": [{"zip":1}], "population":10000}]}
dict2 = {"CA": {"Marin": {"zip":2}}}
Looking at dict2:
- You are given
dict2, containing keyk(in this casek = "CA") dict2[k]itself is a dictionary, that contains one (or more) key (c = "Marin") - value (z) pair(s)znow is the dictionary that you care about.
Looking at dict1:
- For each element
county_infoindict1[k], you care about the one that has a keyc. - The value at this key (
county_info[c]) is a list, to which you want to appendz
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}]}
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))
You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first:
data = { 'obj1' : obj1, 'obj2' : obj2 }
json.dumps(data)
Not sure if I'm missing something, but I think this works (tested in python 2.5) with the output you specify:
import simplejson
finalObj = { 'obj1': obj1, 'obj2': obj2 }
simplejson.dumps(finalObj)
Another solution would be Using dictionary comprehension (Note: This solution will work even if dict has multiple keys and values)
list = [{"name":"New York USA"}, {"id":446}]
data = {}
data['org'] = {key:value for item in list for key, value in item.items()}
print(data)
output: {'org': {'name': 'New York USA', 'id': 446}}
You can use the builtin json library
import json
list_of_dicts = [{},{}]
json_rep = json.dumps(list_of_dicts)