gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:36:37 25 4
gpt4 key购买 nike

我想更新字典,例如:

dict1 = {"brand": "Ford","model": "Mustang","year": 1964}

使用这本词典:
dic2 = {"brand": "Fiat","model": "Toro","color" : "Red","value": 20000}

输出必须是:
dict1 = {"brand": "Fiat","model": "Toro","year": 1964}

我怎样才能做到这一点?

最佳答案

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

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

dict1
{'brand': 'Fiat', 'model': 'Toro', 'year': 1964}

更新:正如所提到的:RoadRunner try: .. except: .. 可以替换为 if i in dic2
for i in dict1:
if i in dic2:
dict1[i] = dic2[i]

关于python - 尝试用更大的字典更新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com