我有字典串列,我想用現有的鍵更新。我嘗試如下,但沒有奏效。有人可以請教
dic1 = [{"valid": 0, "correct": "abc", "other": ["aaa"]}]
dic2 = [ {"correct": "morning", "other":["negative"]}]
dict1.update(dic2)
預期輸出:
[{"valid": 0, "correct": "morning", "other": ["negative"]}]
uj5u.com熱心網友回復:
def update(dic1, dic2):
for i in dic1[0]:
if i in dic2[0]:
dic1[0][i] = dic2[0][i]
return(dic1)
dic1 = update(dic1, dic2)
print(dic1)
嘗試這個
uj5u.com熱心網友回復:
dic1 和 dic2 是串列。您需要在字典update上應用該功能。這應該可以解決您的問題:
dic1 = {"valid": 0, "correct": "abc", "other": ["aaa"]}
dic2 = {"correct": "morning", "other":["negative"]}
dic1.update(dic2)
print (dic1)
uj5u.com熱心網友回復:
dic1[0].update(dic2[0])
print(dic1)
由于串列中只有一個元素,即字典。
#output
[{'correct': 'morning', 'other': ['negative'], 'valid': 0}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447796.html
