Python Forum
Merge two dict with same key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Merge two dict with same key
#1
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
Reply
#2
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#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}
Reply
#4
Thanks!!
Now I understand it looks like when you change the value of a variable.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 73,252 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020