我试图合并两个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}
答案 0 :(得分:10)
IIUC你需要加入dicts,你可以用java.net.ConnectException: failed to connect to android-guru.com/5.230.136.35 (port 80) after 90000ms: isConnected failed: ECONNREFUSED (Connection refused)
来做:
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
更新它,然后使用json.load
保存:
json.dump
答案 1 :(得分:0)
要添加到Anton所说的内容,您可以将json文件读入字典。然后像他一样使用a.update(b)
,并覆盖该文件。
如果你打开要附加的文件,并按照你的方式执行json dump,它将只使用新的json数据创建另一行。
希望这有帮助。
答案 2 :(得分:0)
鉴于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
答案 3 :(得分:0)
可以使用 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}