-1

I merge 2 dictionaries, say d1 and d2 by:

d1.update(d2)

i.e I have:

d1 = {1:'a', 2:'b', 3:'c'}
d2 = {1:'a', 2:'g', 4:'x'}

then after d1.update(d2) I have:

{1: 'a', 2: 'g', 3: 'c', 4: 'x'}

So the original 2:'b' vanished so I'd like to have the translation 'b':'g' somehow, meaning the output will be the following dictionary:

{'b':'g'}

Is there any simple code to keep the overridden values?

Codevan
  • 538
  • 3
  • 20

2 Answers2

4

If {"b":"g} is what you truly wants, you can first use dict comprehension to create it before the update:

d1 = {1:'a', 2:'b', 3:'c'}
d2 = {1:'a', 2:'g', 4:'x'}

ot = {v : d2[k] for k,v in d1.items() if k in d2 and v != d2[k]}
print (ot)

d1.update(d2)
print (d1)

Result:

{'b': 'g'}
{1: 'a', 2: 'g', 3: 'c', 4: 'x'}
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
0
  1. Find the keys that exist in both dictionaries
  2. Create a new dictionary mapping the values from d1 to the values from d2
  3. Remove those key:value pairs where the key and the value are identical
d1 = {1:'a', 2:'b', 3:'c'}
d2 = {1:'a', 2:'g', 4:'x'}

shared_keys = d1.keys() & d2
mapping = {d1[key]: d2[key] for key in shared_keys}
mapping = {k: v for k, v in mapping.items() if k != v}

print(mapping)  # output: {'b': 'g'}
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149