DEV Community

Equivalents in Python and JavaScript. Bonus

Aidas Bendoraitis on February 02, 2019

From time to time I google for the right syntax how to process lists and dictionaries in Python or arrays and objects in JavaScript. So I decide...
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)

Collapse
 
antoinebwodo profile image
Antoine BORDEAU

Great post. You can also use a list comprehension instead of the map or the filter in python. It's a little bit cleaner imo!

Collapse
 
djangotricks profile image
Aidas Bendoraitis

I use list comprehensions quite often and much more often than map or filter. But in this article I was trying to find the closest equivalents of Python and JavaScript. As far as I know, there are no list comprehensions in JavaScript..

Oh wait. There are! developer.mozilla.org/en-US/docs/W...

But unfortunately, they are not supported by any modern browser.

Collapse
 
antoinebwodo profile image
Antoine BORDEAU

OK, I understand 😉

I didn't know either about these javascript functions ! Hope we can really use them one day !

Collapse
 
bay007 profile image
egalicia

Another way!

merged_dicts = {**dictionary_a,**dictionary_b}