0

Is there a faster way in generating a dictionary with a certain default value? I basically want an equavalent of

arrays = [True] * (n+1)

but for dictionary. I currently have:

dicts = dict([(i,True) for i in range(0,n+1)])

The problem is with n = 1000000, the times I am getting with this implementation is 0.016s for the array and 0.318 for the dicts. Is there a faster way to do this for the dictionary?

user1179317
  • 2,693
  • 3
  • 34
  • 62

1 Answers1

1

Yup. dict.fromkeys is designed for this exact use case. Your example dicts could be made directly with:

dicts = dict.fromkeys(range(n + 1), True)

Slightly slower, but more flexible, are dict comprehensions (2.7/3.1+):

dicts = {i: True for i in range(n + 1)}

That will be a little slower in 3.x, and slower than that in 2.x (because True is a keyword in 3.x and doesn't invoke LEGB lookup, but it's only a normal built-in name in 2.x and therefore has to perform multiple dict lookups under the hood on each use, just in case it's been reassigned). dict.fromkeys will be just as fast in either case, because True is only looked up once.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271