I want to update a dicionary, for example:
dict1 = {"brand": "Ford","model": "Mustang","year": 1964}
Using this dictionary:
dic2 = {"brand": "Fiat","model": "Toro","color" : "Red","value": 20000}
The output must be:
dict1 = {"brand": "Fiat","model": "Toro","year": 1964}
How can I do this?
First, you need to iterate over the dictionary you want to update and then replace the key's value (if present).
for i in dict1:
try:
dict1[i] = dic2[i]
except:
pass
dict1
{'brand': 'Fiat', 'model': 'Toro', 'year': 1964}
Update: as mentioned by: RoadRunner try: .. except: ..
could be replaced by if i in dic2
for i in dict1:
if i in dic2:
dict1[i] = dic2[i]
you can use a dictionary comprehension using dict.get
method:
dict1 = {k : dic2.get(k, v) for k, v in dict1.items()}
# {'brand': 'Fiat', 'model': 'Toro', 'year': 1964}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With