Trying to update a dictionary with bigger dictionary

Viewed 67

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?

4 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]

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}

An easy solution would be to just loop over the intersected keys and update dict1:

for key in dict1.keys() & dic2.keys():
    dict1[key] = dic2[key]

print(dict1)
# {'brand': 'Fiat', 'model': 'Toro', 'year': 1964}

or simply just check if the key exists before updating:

for key in dict1:
    if key in dic2:
        dict1[key] = dic2[key]

print(dict1)
# {'brand': 'Fiat', 'model': 'Toro', 'year': 1964}

Solution with dict comprehension:

dict1 = {"brand": "Ford","model": "Mustang","year": 1964}
dict2 = {"brand": "Fiat","model": "Toro","color" : "Red","value": 20000}

dict3 = {k:dict2[k] if k in dict2 else dict1[k] for k in dict1}
Related