组合两个json字典python

2024-05-15 04:56:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试合并两个json字典。到目前为止,我有一个json文件(myjfile.json),其中包含

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

另外,我还有一本python字典(mydict),如下所示:

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

当我把两者结合起来时,它们是两本不同的词典

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

请注意,myfile.json在代码中是用“a”和a/n编写的,因为我希望保留文件的内容,并在每次写入该文件时开始一行。

我希望最终结果看起来像

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

Tags: 文件json字典withmyfilecarsmydictstores
3条回答

如果你需要加入到dicts中,你可以使用update

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

a.update(b)
print(a)

输出如下:

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

要创建全新的dict而无需触摸a,您可以执行以下操作:

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

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

编辑

对于您的情况,可以用json.load加载json并更新它,然后用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)

鉴于OP的问题有一个包含JSON内容的文件,这个答案可能更好:

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)

此外,由于这是增量的,因此可以通过以下有效的帮助函数获取文件的最后一行:

# 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

为了补充安东所说的,您可以将json文件读入字典。然后像他那样使用a.update(b),并覆盖文件。

如果您打开要追加的文件,并像您所做的那样进行json转储,那么它将使用新的json数据创建另一行。

希望这有帮助。

相关问题 更多 >

    热门问题