尝试用更大的字典更新字典

Mat*_*nio 4 python dictionary

我想更新字典,例如:

dict1 = {"brand": "Ford","model": "Mustang","year": 1964}
Run Code Online (Sandbox Code Playgroud)

使用这本词典:

dic2 = {"brand": "Fiat","model": "Toro","color" : "Red","value": 20000}
Run Code Online (Sandbox Code Playgroud)

输出必须是:

dict1 = {"brand": "Fiat","model": "Toro","year": 1964}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

OmO*_*ker 7

首先,您需要遍历要更新的字典,然后替换键的值(如果存在)。

for i in dict1:
    try:
        dict1[i] = dic2[i]
    except:
        pass

dict1
{'brand': 'Fiat', 'model': 'Toro', 'year': 1964}
Run Code Online (Sandbox Code Playgroud)

更新:正如所提到的:RoadRunnertry: .. except: ..可以被替换为if i in dic2

for i in dict1:
    if i in dic2:
        dict1[i] = dic2[i]
Run Code Online (Sandbox Code Playgroud)