Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why defaultdict constructor takes a function and not a constant

This is how defaultdict works:

from collections import defaultdict
a=defaultdict(lambda:3)
a[200]==3 #True

Why is it that defaultdict was designed to take a function with no arguments, and not simply a constant value?


Here's the alternative definition.

class dd(dict):
    def __init__(self,x):
        self._default=x
    def __getitem__(self,key):
        if key in self: return dict.__getitem__(self, key)
        else:
            self[key]=self._default
            return self[key]

So that

a=dd(3)
a[200]==3 #True
like image 615
KalEl Avatar asked Sep 14 '13 02:09

KalEl


People also ask

How does the Defaultdict work?

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.

What is the difference between Defaultdict and dict?

The functionality of both dictionaries and defaultdict are almost the same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exist. Parameters: default_factory: A function returning the default value for the dictionary defined.

Is Defaultdict faster than dict?

setdefault() , and the second uses a defaultdict . The time measure will depend on your current hardware, but you can see here that defaultdict is faster than dict.

What is the use of Defaultdict in Python?

The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int.


1 Answers

Because if you want the default value to be a mutable object, you probably want it to be a different mutable object for each key.

If you passed a constant and did defaultdict([]), then every time a missing key was accessed, its value would be set to the same list. Then you'd get this:

>>> d = defaultdict([])
>>> d[1].append("Whoops")
>>> print d[2]
["Whoops"]

Having a mutable default value is in fact very common and useful, since it lets you do things like d[key].append("Blah") without having to first check that d[key] exists. For this case, you need some way to return a new value each time, and the simplest way to do that is to have a callable that returns a default value.

like image 154
BrenBarn Avatar answered Oct 21 '22 05:10

BrenBarn