Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a defaultdict from a dictionary?

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?

like image 539
Karthick Avatar asked Sep 24 '11 12:09

Karthick


People also ask

How does Defaultdict work Defaultdict stores a copy of a dictionary?

Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exists.

What is the difference between dictionary and Defaultdict?

So, you can say that defaultdict is much like an ordinary dictionary. The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key .

Is Defaultdict a dict?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.


1 Answers

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) 
like image 151
Jochen Ritzel Avatar answered Oct 10 '22 00:10

Jochen Ritzel