hjelpmig
hjelpmig

Reputation: 1455

check two dictionaries that have similar keys but different values

I have two dictionaries. dict1 and dict2. dict 2 is always of the same length but dict1 varies in length. Both dictionaries are as follows:

dict2 = {"name":"martin","sex":"male","age":"97","address":"blablabla"}

dict1 = {"name":"falak", "sex":"female"}

I want to create a third dictionary that is based on both dict1 and dict2. dict3 will have all values of dict2. But all those keys will be replaced that exists in dict1. Here is the resulting dict3

dict3 = {"name":"falak","sex":"female","age":"97","address":"blablabla"}

I can do it wil multiple if statements but want to have a way that is more smarter. Can please someone guide me regarding that.

Upvotes: 4

Views: 531

Answers (4)

Mariano Anaya
Mariano Anaya

Reputation: 1296

import copy
dict3 = copy.copy(dict2)
dict3.update(dict1)

Upvotes: 1

kiriloff
kiriloff

Reputation: 26335

First, you add items from d1 that have keys not present in d2. All other keys from d1 are in d2.

Then, you add all keys from d2, with value from d2 if no such key in d1, with value from d1 if key exists in d1.

dict2 = {"name":"martin","sex":"male","age":"97","address":"blablabla"}
dict1 = {"name":"falak", "sex":"female"}

dic = dict()

for key, val in dict1.items():
  if key not in dict2.keys():
    dic[key] = val

for key, val in dict2.items():
  if key not in dict1.keys():
    dic[key] = val
  else:
    dic[key] = dict1[key]

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81916

From the python documentation:

update([other])

  • Update the dictionary with the key/value pairs from other, overwriting existing keys.
  • Returns None.
  • update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
  • Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.

So:

dict1.update(dict2)

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142126

Have you tried:

dict3 = dict(dict2, **dict1)

Or:

dict3 = dict2.copy()
dict3.update(dict1)

Upvotes: 11

Related Questions