13

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}
3
  • What about a.update(b) for your dicts? Commented Jan 20, 2016 at 20:25
  • You need to load into memory your json from file, apply update and then save it un file. Thats how it works. Commented Jan 20, 2016 at 20:31
  • All you need is to load the last line from your file and update it with your local dict. See solution attached. Commented Jan 20, 2016 at 20:47

4 Answers 4

21

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)
   
Sign up to request clarification or add additional context in comments.

4 Comments

Dont i need a with open() statement?
You first need to read your json then update it and write it back. You could just add your dict to the existed file. Or would you like to place full dict in the second line?
Since the first set of data(cars, houses etc,) was already being generated into a json early on, i just want to append mydict to what has been generated.
It generates the first set of data-myjsonfile.json- with a with open() statement, so not sure where to add the update, if i add it outside the with open i get object has no attribute update.
0

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.

Comments

0

Given OP's question has a file with JSON contents this answer might be better:

import json
import ast

myFile = 'myFile.json'
jsonString = lastLineofFile(myfile)
d = ast.literal_eval(jsonString) # from file

d.update(dict)
with open(myFile, 'a') as f:
    json.dump(d, f)

Also, since this is incremental, the last line of file can be obtained by the following efficient helper function:

# Read the last line of a file. Return 0 if not read in 'timeout' number of seconds
def lastLineOfFile(fileName, timeout = 1):
    elapsed_time = 0
    offset = 0 
    line = '' 
    start_time = time.time()

    with open(fileName) as f: 
        while True and elapsed_time < timeout: 
            offset -= 1 
            f.seek(offset, 2) 
            nextline = f.next() 

            if nextline == '\n' and line.strip(): 
                return line 
            else: 
                line = nextline

            elapsed_time = time.time() - start_time

    if elapsed_time >= timeout:
        return None

Comments

0

It can be done using something like the spread operator in JavaScript:

In [2]: a = {"cars": 1, "houses": 2, "schools": 3, "stores": 4}

In [3]: b = {"Pens": 1, "Pencils": 2, "Paper": 3}

In [4]: {**a, **b}
Out[4]:
{'cars': 1,
 'houses': 2,
 'schools': 3,
 'stores': 4,
 'Pens': 1,
 'Pencils': 2,
 'Paper': 3}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.