Skip to content
Advertisement

is there a faster way to get multiple keys from dictionary?

I have a dictionary:

JavaScript

Then I have a list of keys:

JavaScript

My desired result is:

JavaScript

What I’m doing so far is:

JavaScript

Is there a faster way? Perhaps without for?

Advertisement

Answer

You could use:

JavaScript

It has two advantages:

  • It performs the d.get lookup only once – not each iteration
  • Only CPython: Because dict.get is implemented in C and map is implemented in C it can avoid the Python layer in the function call (roughly speaking the details are a bit more complicated).

As for timings (performed on Python 3.6 in a Jupyter notebook):

JavaScript

Note that this is actually slower in this case! That’s because for short iterables the map and list overhead dominate. So if you want it faster on short iterables stick with your approach.

With longer l you see that list(map(...)) eventually becomes faster:

JavaScript

However that’s still “just” a factor of 2 faster.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement