Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two JSON dictionaries in Python?

I'm trying to combine two JSON dictionaries. So far I have a JSON file(myjfile.json) with the contents

{"cars": 1, "houses": 2, "schools": 3, "stores": 4}

Also, I have a dictionary(mydict) in Python which looks like this:

{"Pens": 1, "Pencils": 2, "Paper": 3}

When I combine the two, they are two different dictionaries.

with open('myfile.json' , 'a') as f:
  json.dump(mydict, f)

Note that the myfile.json is being written with 'a' and a /n in the code because I want to keep the contents of the file and start a new line each time it's being written to.

I want the final result to look like

{"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Pencils": 2, "Paper": 3}
like image 510
jumpman8947 Avatar asked Jan 20 '16 20:01

jumpman8947


1 Answers

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)
   
like image 70
Anton Protopopov Avatar answered Oct 28 '22 12:10

Anton Protopopov