-1

Say there are two dictionaries.

dict1 = {'a':1,'b':2,'c':3,'d':4}

dict2 = {'a':1,'b':'yellow','c':3,'e':5}

How would one append values in dict2 to dict1 while also replacing new values with equal keys.

Intended Result: dict1 = {'a':1,'b':'yellow','c':3,'d':4,e':5}

Been struggling with this one for a while.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45

2 Answers2

4

Unpack the dictionaries in the order you want them to be superseded:

dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'a':1,'b':'yellow','c':3,'e':5}
result = {**dict1,**dict2}
print(result)
Lucas Ng
  • 671
  • 4
  • 11
0
dict1 = {'a':1,'b':2,'c':3,'d':4, 'f':6}
dict2 = {'a':1,'b':'yellow','c':3,'e':5}

k1 = dict1.keys()
k2 = dict2.keys()
keys_diff = list(set(k1) - set(k2))
for key in keys_diff:
  dict2[key] = dict1[key]
dict2
Zal78
  • 77
  • 1
  • 5
  • 1
    While this should work, it's doing a lot of unnecessary work creating the sets and set difference. It's enough to just overwrite all existing keys with the value in `dict2`, since writing to a dict replaces any pre-existing values. – joanis May 09 '21 at 19:46