112

If I have d=dict(zip(range(1,10),range(50,61))) how can I build a collections.defaultdict out of the dict?

The only argument defaultdict seems to take is the factory function, will I have to initialize and then go through the original d and update the defaultdict?

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
Karthick
  • 4,456
  • 7
  • 28
  • 34

3 Answers3

123

Read the docs:

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

from collections import defaultdict
d=defaultdict(int, zip(range(1,10),range(50,61)))

Or given a dictionary d:

from collections import defaultdict
d=dict(zip(range(1,10),range(50,61)))
my_default_dict = defaultdict(int,d)
Oded BD
  • 2,788
  • 27
  • 30
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • 3
    Is it possible to extend this approach for nested dicts? The following doesn't work as intended: `default_dict = defaultdict(None,{"a":1,"b":{"c":3}})` for example `default_dict["e"]` raises a KeyError instead returning None – alancalvitti Dec 28 '18 at 16:13
  • 8
    @alancalvitti that's because passing `None` doesn't mean that it will generate None for unknown keys, it will not use one at all. You need to do `defaultdict(lambda: None, {....})` – Eric Darchis Jan 15 '19 at 10:47
16

You can construct a defaultdict from dict, by passing the dict as the second argument.

from collections import defaultdict

d1 = {'foo': 17}
d2 = defaultdict(int, d1)

print(d2['foo'])  ## should print 17
print(d2['bar'])  ## should print 1 (default int val )
muhsin mohammed
  • 161
  • 1
  • 3
-1

You can create a defaultdict with a dictionary by using a callable.

from collections import defaultdict

def dict_():
    return {'foo': 1}

defaultdict_with_dict = defaultdict(dict_)
hoi ja
  • 239
  • 5
  • 8