当前位置: 动力学知识库 > 问答 > 编程问答 >

combine two json dictionary python

问题描述:

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

{"cars": 01, "houses": 02, "schools": 03, "stores": 04}

Also i have a dictionary(mydict) in python which look 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 its being written to.

I want the final result to look like

{"cars": 01, "houses": 02, "schools": 03, "stores": 04, "Pens": 1, "Pencils": 2, "Paper": 3}

网友答案:

IIUC you need to join to 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 touch 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 you 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.

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: