Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to update a dictionary with bigger dictionary

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?

like image 423
Matheus Epifanio Avatar asked Dec 14 '22 09:12

Matheus Epifanio


2 Answers

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]
like image 123
OmO Walker Avatar answered Dec 25 '22 08:12

OmO Walker


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}
like image 27
kederrac Avatar answered Dec 25 '22 10:12

kederrac