2

I want to use a defaultdict to initialize a dictionary.

d = collections.defaultdict(set)

for i in range(3):
  d[i].add(True)

This would result in a dictionary with keys 1..3 and values of {True} for each. Later I want to iterate through the values of this set like so:

for b in d[10]:
  print(b)

In a standard dictionary, this would throw because 10 is not a key of the dict. In a default dict, this would initialize 10 with an empty set and not throw.

Is there a way to "lock in" the keys of a defaultdict without copying all of the keys to a new dict? Is d = dict(d) an O(1) op?

micah
  • 7,596
  • 10
  • 49
  • 90
  • 1
    Does this answer your question? [How to convert defaultdict to dict?](https://stackoverflow.com/questions/20428636/how-to-convert-defaultdict-to-dict) – Silvio Mayolo Sep 12 '21 at 20:47
  • `defaultdict` is a subclass of `dict`, not a wrapper around an ordinary `dict`. If the later were true, you could simply extract a reference to the wrapped `dict` and discard the `defaultdict`. – chepner Sep 12 '21 at 20:58

1 Answers1

3

It is not an O(1) operation, as a new dict is created by copying the existing keys and values from the default dict. A demonstration:

>>> d = collections.defaultdict(set)
>>> for i in range(3):
...    d[i].add(True)
...
>>> d2 = dict(d)
>>> d[10].add(9)  # Modify the default dict
>>> d
defaultdict(<class 'set'>, {0: {True}, 1: {True}, 2: {True}, 10: {9}})
>>> d2
{0: {True}, 1: {True}, 2: {True}}

As you can see, d is modified, but not the dict created from d before the modification was made.

chepner
  • 497,756
  • 71
  • 530
  • 681