Python Forum

Full Version: Merge two dict with same key
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I see this code to merge two dict with same key and I don't understand ,why in the final result is the key to the second dictionary (key b) taken as a final key?
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}
The result is:
>>> z
{'c': 4, 'a': 1, 'b': 3}
Regards,
RavCoder
you unpack arguments from left to right
so it start to unpack x first and key 'b' value is 2, then it start to unpack y and the value for key 'b' is overwritten with the new value 3
By unpacking each dictionary in that manner, you're essentially doing this:

{'a': 1, 'b': 2, 'b': 3, 'c': 4}
In that case, the interpreter is going to:
  1. Initialize the dict
  2. Set key "b" to 2
  3. Reset key "b" to 3

If you reverse the order of x and y, you'll get the opposite result:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**y, **x}
print(z)
Output:
{'b': 2, 'c': 4, 'a': 1}
Thanks!!
Now I understand it looks like when you change the value of a variable.