Skip to content

Instantly share code, notes, and snippets.

@dschep
Last active June 2, 2023 15:57
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dschep/4288afe9923738dea1092ed55f1efeef to your computer and use it in GitHub Desktop.
Save dschep/4288afe9923738dea1092ed55f1efeef to your computer and use it in GitHub Desktop.
Python Comprehensions to JS

Python list & dict comprehensions translated to JavasScript

Comprehensions are a really useful feature of Python that aren't available in JavaScript (or many languages). These concepts of course can be tranlsated into using map instead. But especially the dictionaries are a bit trickier.

Lists / Arrays

>>> foobar = range(5)
>>> [x + 1 for x in foobar]
[1, 2, 3, 4, 5]
# Intermediate translation
>>> map(lambda x: x + 1, foobar)
[1, 2, 3, 4, 5]

becomes:

> foobar = [0, 5, 3, 2]
[ 0, 5, 3, 2 ]
> foobar.map(x => x+1)
[ 1, 6, 4, 3 ]

Dictionaries / Objects

foobar = [{'key': 'fasdf', 'value': 'asfasdfaf'}, {'key': 'fassdfsddf', 'value': 'asdfaf'}]
>>> {x['key']: x['value'] for x in foobar}
{'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}
>>> # Intermediate translation to map
... dict(map(lambda x: (x['key'], x['value']), foobar))
{'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}

becomes:

> foobar = [{'key': 'fasdf', 'value': 'asfasdfaf'}, {'key': 'fassdfsddf', 'value': 'asdfaf'}]
[ { key: 'fasdf', value: 'asfasdfaf' },
  { key: 'fassdfsddf', value: 'asdfaf' } ]
> Object.fromEntries(foobar.map(x => [x.key, x.value]))
{ fasdf: 'asfasdfaf', fassdfsddf: 'asdfaf' }

dict->dict / obj->obj

>>> foobar = {'fasdf': 'asfasdfaf', 'fassdfsddf': 'asdfaf'}
>>> {key: val.upper() for key, val in foobar.items()}
{'fasdf': 'ASFASDFAF', 'fassdfsddf': 'ASDFAF'}

becomes:

foobar = {fasdf: 'asfasdfaf', fassdfsddf: 'asdfaf'}
Object.fromEntries(Object.entries(foobar).map(([key, value]) => [key, value.toUpperCase()]))
{ fasdf: 'ASFASDFAF', fassdfsddf: 'ASDFAF' }
@dwolfand
Copy link

dwolfand commented May 5, 2017

Very cool!

@jmndao
Copy link

jmndao commented Nov 5, 2021

Very instructive. Thank you

@dschep
Copy link
Author

dschep commented Nov 8, 2021

@jmndao thanks, but note, that _.fromPairs can now be replaced with Object.fromEntires(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries). I've updated this gist to reflect that

@jmndao
Copy link

jmndao commented Nov 9, 2021

Dope, Thanks again. Will surely take a look.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment