Merge two dict with same key - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Merge two dict with same key (/thread-21703.html) |
Merge two dict with same key - RavCOder - Oct-10-2019 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 RE: Merge two dict with same key - buran - Oct-10-2019 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 RE: Merge two dict with same key - stullis - Oct-10-2019 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:
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)
RE: Merge two dict with same key - RavCOder - Oct-10-2019 Thanks!! Now I understand it looks like when you change the value of a variable. |