DEV Community

Discussion on: Equivalents in Python and JavaScript. Bonus

Collapse
 
svinci profile image
Sebastian G. Vinci • Edited

Great post! Just a side note regarding dictionary merging.

In python 3.5 or greater you can merge dictionaries by doing this:

>>> a = {1: 1, 2: 2}
>>> b = {2: 2, 3: 3}
>>> {**a, **b}
{1: 1, 2: 2, 3: 3}
>>>

Kind of like a spread operator.

For python 3.4 and below a simpler solution would look like this:

>>> c = a.copy()
>>> c.update(b)
>>> c
{1: 1, 2: 2, 3: 3}
>>>

(The copy is only there to prevent mutation of the original dictionaries, but if you are fine with the mutation, you can skip that step and just update a with b)