【问题标题】:Combine two JSON dictionaries in Python?在 Python 中结合两个 JSON 字典?
【发布时间】:2016-04-26 20:56:49
【问题描述】:

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

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

另外,我在 Python 中有一个字典(mydict),看起来像这样:

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

当我将两者结合起来时,它们是两个不同的字典。

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

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

我希望最终结果看起来像

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

【问题讨论】:

  • 你的dictsa.update(b)怎么样?
  • 您需要将您的 json 从文件加载到内存中,应用更新,然后将其保存为文件。这就是它的工作原理。
  • 所有你需要的是从你的文件中加载最后一行并用你的本地字典更新它。请参阅随附的解决方案。

标签: python json dictionary


【解决方案1】:

IIUC 你需要将两个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)
   

【讨论】:

  • 我不需要 with open() 语句吗?
  • 您首先需要读取您的 json,然后对其进行更新并将其写回。您可以将您的 dict 添加到现有文件中。或者你想把完整的字典放在第二行吗?
  • 由于第一组数据(汽车、房屋等)已经在早期生成为 json,我只想将 mydict 附加到已生成的内容中。
  • 它使用 with open() 语句生成第一组 data-myjsonfile.json-,所以不确定在哪里添加更新,如果我在 with open 之外添加它,我得到的对象没有属性更新。
【解决方案2】:

要补充 Anton 所说的内容,您可以将 json 文件读入字典。然后像他一样使用a.update(b),并覆盖文件。

如果您打开要追加的文件,并像您拥有的那样执行 json 转储,则只会使用新的 json 数据创建另一行。

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    鉴于 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
    

    【讨论】:

      【解决方案4】:

      这可以使用 JavaScript 中的 spread operator 之类的东西来完成:

      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}
      

      【讨论】:

        猜你喜欢
        • 2022-12-26
        • 1970-01-01
        • 2019-05-16
        • 2019-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 2017-07-23
        相关资源
        最近更新 更多