+ 4
[🐍PyTricks]: Merging two dictionaries in Python 3.5+ with a single expression
# How to merge two dictionaries # in Python 3.5+ >>> x = {'a': 1, 'b': 2} >>> y = {'b': 3, 'c': 4} >>> z = {**x, **y} >>> z {'c': 4, 'a': 1, 'b': 3} # In Python 2.x you could # use this: >>> z = dict(x, **y) >>> z {'a': 1, 'c': 4, 'b': 3} # In these examples, Python merges dictionary keys # in the order listed in the expression, overwriting # duplicates from left to right. #
11 Respuestas
+ 10
Hi! You can submit these as lessons in the lesson factory. Thanks.
+ 5
I would like such an obfuscated approach if it was perl, not python ;)
what's wrong with a built-in update method?
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}
>>> x.update(y)
>>> x
{'a': 1, 'b': 3, 'c': 4}
+ 1
update has issues only if you want to only *copy* the dictionnaires and keep them unchanged. Then, the code is either inelegant, or not really efficient
+ 1
rahul kumar LOL why you answering after 2 years.🤣😅😂😂
0
It is actually the most efficient and the most explicit method to merge dictionaries...
I have read an article (or watched a talk, I'm not sure which one) about precisely that, and there ARE problems with update...
0
@Amaras A
Could you please elaborate on his point? I will appreciate it.
0
@Maxim Zinyakov: well, there are some test, run them if you want to check https://gist.github.com/bnorick/adfe68808916621d369e
And it actually has issues only if you want both dictionaries left untouched and have an elegant solution.
0
@Amaras A
I still can't get your point. I see no "issues" with update method except it is a little bit slower then kwargs hack when merging _empty_ dictionaries. In other cases it is more effective.
https://code.sololearn.com/cBx0ayFF7Ps1/?ref=app
Note: this code gets time exceeded error on SoloLearn site, so try it locally.
0
Don’t use ** unpack. Even Guido doesn’t suggest this method to do dictionary addition.
0
why though? it's fast, correct and there is no reason not to use it. Has Guido said it should not be used @Chenghua Yang?
0
PEP 448 also expanded the abilities of ** by allowing this operator to be used for dumping key/value pairs from one dictionary into a new dictionary . Leveraging dictionary comprehension and the unpacking operator, you can merge the two dictionaries in a single expression .
>>>dict1 = {1:'one' , 2:'two'}
>>>dict2 = {3:'three', 4:'four'}
>>>fDict = {**dict1 , **dict2}
>>>print(fDict)
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
http://net-informations.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ds/merge.htm