DEV Community

Aidas Bendoraitis
Aidas Bendoraitis

Posted on • Originally published at djangotricks.blogspot.com on

Equivalents in Python and JavaScript. Bonus

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 decided to extend my series of equivalents with those functions. After all, it's me too, who will be using the information I provide here.

All truthful elements

Sometimes we need to check from a list of conditions if all of them are true, or from a list of elements if all of them are not empty.

This can be checked with the following in Python:

items = [1, 2, 3]
all_truthy = all(items)
# True
Enter fullscreen mode Exit fullscreen mode

And here is an equivalent in JavaScript:

items = [1, 2, 3];
all_truthy = items.every(Boolean);
// true
Enter fullscreen mode Exit fullscreen mode

Any truthful elements

Similarly, we can check if at least one of the conditions is true, or there is at least one non-empty element in a list.

It Python we would do that with:

items = [0, 1, 2, 3]
some_truthy = any(items)
# True
Enter fullscreen mode Exit fullscreen mode

And in JavaScript we would check it like this:

items = [0, 1, 2, 3];
some_truthy = items.some(Boolean);
// true
Enter fullscreen mode Exit fullscreen mode

Iterate through each element and its index

Here is an example of how to iterate through a list of items and also check their indices in Python. It is useful for verbose console output when creating different command line tools that process data:

items = ['a', 'b', 'c', 'd']
for index, element in enumerate(items):
    print(f'{index}: {element};')
Enter fullscreen mode Exit fullscreen mode

In JavaScript an analogous way to do the same would be using the forEach() method. The usual for loop is also an option, but I find the forEach() more elegant and clear.

items = ['a', 'b', 'c', 'd'];
items.forEach(function(element, index) {
    console.log(`${index}: ${element};`);
});
Enter fullscreen mode Exit fullscreen mode

Map elements to the results of a function

To process all elements of a list, you can either iterate through them with the for loop and create a new list with modifications, or you can do that in one step by mapping the list items to a modification function. In Python this can be done with the map() function:

items = [0, 1, 2, 3]
all_doubled = list(map(lambda x: 2 * x, items))
# [0, 2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

In JavaScript the map() is a method of an array:

items = [0, 1, 2, 3];
all_doubled = items.map(x => 2 * x);
// [0, 2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

Filter elements by a function

When you need to search for some elements in a list or array and want to avoid for loops, you can use the filtering functionality. In Python that is doable with the filter() function that accepts the filtering function and the list and returns a new filtered list.

items = [0, 1, 2, 3]
only_even = list(filter(lambda x: x % 2 == 0, items))
# [0, 2]
Enter fullscreen mode Exit fullscreen mode

In JavaScript there is a filter() method of the array for that.

items = [0, 1, 2, 3];
only_even = items.filter(x => x % 2 === 0);
// [0, 2]
Enter fullscreen mode Exit fullscreen mode

In both cases, the filtering function checks each item if it is matching the filter criteria and returns true in that case.

Reduce elements by a function to a single value

When you want to apply some function to a list of items to get a single result in one go, you can use the reduce function. It works for summing, multiplying, ORing, ANDing, or checking maximums and minimums.

In Python there is a reduce() function for that.

from functools import reduce
items = [1, 2, 3, 4]
total = reduce(lambda total, current: total + current, items)
# 10
Enter fullscreen mode Exit fullscreen mode

In JavaScript there is a reduce() method of the array.

items = [1, 2, 3, 4];
total = items.reduce((total, current) => total + current);
// 10
Enter fullscreen mode Exit fullscreen mode

Merge dictionaries

There are multiple ways to merge dictionaries in Python or objects in JavaScript. But these are probably the simplest ones.

In Python it's decomposing dictionaries to tuples of keys and arrays, joining them, and creating a new dictionary.

d1 = {'a': 'A', 'b': 'B'}
d2 = {'a': 'AAA', 'c': 'CCC'}
merged = dict(list(d1.items()) + list(d2.items()))
# {'a': 'AAA', 'b': 'B', 'c': 'CCC'}
Enter fullscreen mode Exit fullscreen mode

Analogously, in JavaScript it's spreading two objects into a new object:

d1 = {a: 'A', b: 'B'}
d2 = {a: 'AAA', c: 'CCC'}
merged = {...d1, ...d2};
// {a: 'AAA', b: 'B', c: 'CCC'}
Enter fullscreen mode Exit fullscreen mode

The Takeaways

  • In both languages, you can traverse through lists of items without explicitly incrementing and referencing an index.
  • For processing list items, you don't necessarily need a loop. The dedicated methods or functions all() / every(), any() / some(), map(), filter(), and reduce() are there to help you.
  • In both languages, you can merge multiple dictionaries into one. If the same key appears in several dictionaries, the latest one will be used in the merged dictionary.

Of course, I also updated the cheat sheet with the full list of equivalents in Python and JavaScript that you saw here described. This cheat sheet helps me with a good overview next to my laptop, so I believe that it would be helpful to you too. The new revision 10 is with syntax highlighting, so it makes it even better to explore and understand.

✨✨✨
Get the Ultimate Cheat Sheet of
Equivalents in Python and JavaScript
✨✨✨

Use it for good!


Cover photo by Darren Chan.

Top comments (5)

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}