How does collections.defaultdict work?Understanding the use of defaultdict in PythonAppending elements to an empty dictionary of lists in PythonWhat is the purpose and use of **kwargs?What is a “callable”?python format string unused named argumentsWhat is the purpose of collections.ChainMap?Exposing `defaultdict` as a regular `dict`Python defaultdict that does not insert missing valuesCast value if it is not None in pythonPython AttributeError: 'dict' object has no attribute 'append'How to merge two dictionaries in a single expression?How do I efficiently iterate over each entry in a Java Map?How do I check whether a file exists without exceptions?What does the “yield” keyword do?How do I return multiple values from a function?Does Python have a ternary conditional operator?What does if __name__ == “__main__”: do?How do I sort a dictionary by value?How do I list all files of a directory?Does Python have a string 'contains' substring method?
Do I have to rename all creatures in a new world?
What's the point of this macro?
Why there is no wireless switch?
Is directly echoing the user agent in PHP a security hole?
'Hard work never hurt anyone' Why not 'hurts'?
Is every coset of a group closed under taking inverses?
Professor refuses to write a recommendation letter
Was "The Hobbit" ever abridged?
How many people can lift Thor's hammer?
Numerical minimum of a one-valued function
'This one' as a pronoun
How could a planet have one hemisphere way warmer than the other without the planet being tidally locked?
Where on Earth is it easiest to survive in the wilderness?
To which airspace does the border of two adjacent airspaces belong to?
How does the UK House of Commons think they can prolong the deadline of Brexit?
Zermelo's proof for unique factorisation
A Meal fit for a King
Why there are construction cranes on apparently completed buildings in New York?
Fantasy Military Arms and Armor: the Dwarven Grand Armory
Who are these people in this satirical cartoon of the Congress of Verona?
Are treasury bonds more liquid than USD?
What would a biological creature need in order to see into the future?
Is there any reason to change the ISO manually?
How do I anonymously report the Establishment Clause being broken?
How does collections.defaultdict work?
Understanding the use of defaultdict in PythonAppending elements to an empty dictionary of lists in PythonWhat is the purpose and use of **kwargs?What is a “callable”?python format string unused named argumentsWhat is the purpose of collections.ChainMap?Exposing `defaultdict` as a regular `dict`Python defaultdict that does not insert missing valuesCast value if it is not None in pythonPython AttributeError: 'dict' object has no attribute 'append'How to merge two dictionaries in a single expression?How do I efficiently iterate over each entry in a Java Map?How do I check whether a file exists without exceptions?What does the “yield” keyword do?How do I return multiple values from a function?Does Python have a ternary conditional operator?What does if __name__ == “__main__”: do?How do I sort a dictionary by value?How do I list all files of a directory?Does Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs
>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
and
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
the parameters int
and list
are for what?
python dictionary default-value defaultdict
add a comment |
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs
>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
and
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
the parameters int
and list
are for what?
python dictionary default-value defaultdict
9
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting itsdefault_factory = None
after you've finished populating the defaultdict. See this question.
– Acumenus
Oct 30 '16 at 5:54
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05
add a comment |
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs
>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
and
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
the parameters int
and list
are for what?
python dictionary default-value defaultdict
I've read the examples in python docs, but still can't figure out what this method means. Can somebody help? Here are two examples from the python docs
>>> from collections import defaultdict
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
and
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
the parameters int
and list
are for what?
python dictionary default-value defaultdict
python dictionary default-value defaultdict
edited Oct 31 '17 at 14:39
Brian Burns
8,1175 gold badges50 silver badges48 bronze badges
8,1175 gold badges50 silver badges48 bronze badges
asked May 5 '11 at 15:45
LanstonLanston
3,4717 gold badges24 silver badges36 bronze badges
3,4717 gold badges24 silver badges36 bronze badges
9
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting itsdefault_factory = None
after you've finished populating the defaultdict. See this question.
– Acumenus
Oct 30 '16 at 5:54
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05
add a comment |
9
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting itsdefault_factory = None
after you've finished populating the defaultdict. See this question.
– Acumenus
Oct 30 '16 at 5:54
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05
9
9
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting its
default_factory = None
after you've finished populating the defaultdict. See this question.– Acumenus
Oct 30 '16 at 5:54
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting its
default_factory = None
after you've finished populating the defaultdict. See this question.– Acumenus
Oct 30 '16 at 5:54
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05
add a comment |
14 Answers
14
active
oldest
votes
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
@Ambareeshd.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged.defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.
– Sven Marnach
May 2 at 19:10
add a comment |
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict =
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned0
the integer, if it wassomeddict = defaultdict(list)
it returns[ ]
. Is 0 the default integer? Or [ ] the default list?
– Gathide
Jan 5 '17 at 7:30
Neither.0
is immutable - in CPython all values from-5
to256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time withint()
orlist()
. That way,d[k].append(v)
can work without filling the dictionary with references to the same list, which would renderdefaultdict
almost useless. If this were the behaviour,defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)
– wizzwizz4
Oct 7 '17 at 8:58
add a comment |
defaultdict
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict
lets the caller specify the default(value to be returned) up front when the container is initialized."
as defined by Doug Hellmann in The Python Standard Library by Example
How to use defaultdict
Import defaultdict
>>> from collections import defaultdict
Initialize defaultdict
Initialize it by passing
callable as its first argument(mandatory)
>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
>>> def foo():
... return 'default value'
...
>>> d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, )
>>> d_list
defaultdict(<type 'list'>, )
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, )
**kwargs as its second argument(optional)
>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
or
>>> kwargs = 'a':10,'b':12,'c':13
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
How does it works
As is a child class of standard dictionary, it can perform all the same functions.
But in case of passing an unknown key it returns the default value instead of error. For ex:
>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12, 'd': 0)
In case you want to change default value overwrite default_factory:
>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0)
or
>>> def foo():
... return 2
>>> d_int.default_factory = foo
>>> d_int['f']
2
>>> d_int
defaultdict(<function foo at 0x7f34a0a0a140>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0, 'f': 2)
Examples in the Question
Example 1
As int has been passed as default_factory, any unknown key will return 0 by default.
Now as the string is passed in the loop, it will increase the count of those alphabets in d.
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> d.default_factory
<type 'int'>
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
>>> d
defaultdict(<type 'int'>, 'i': 4, 'p': 2, 's': 4, 'm': 1)
Example 2
As a list has been passed as default_factory, any unknown(non-existent) key will return [ ](ie. list) by default.
Now as the list of tuples is passed in the loop, it will append the value in the d[color]
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> d.default_factory
<type 'list'>
>>> for k, v in s:
... d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d
defaultdict(<type 'list'>, 'blue': [2, 4], 'red': [1], 'yellow': [1, 3])
add a comment |
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
add a comment |
Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.
It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations.
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.
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print(ice_cream['Sarah'])
>>>Chunky Monkey
print(ice_cream['Joe'])
>>>Vanilla
Here is another example on How using defaultdict, we can reduce complexity
from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
result = []
counts = defaultdict(int)
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))
In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.
add a comment |
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, )
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, )
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, 'a': 0)
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, )
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, 'a': 0)
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, )
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, 'a': 1)
>>>
add a comment |
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
add a comment |
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option)
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, 'eggs': 1, 'spam': 7)
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.
add a comment |
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9)
import collections
d =
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
add a comment |
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Herelist
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of1
, you'd uselambda:1
which is obviously not a type.
– antoine-sac
Sep 5 '18 at 9:55
add a comment |
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
add a comment |
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
add a comment |
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, 'foo': 'bar')
foo => bar
bar => default value
add a comment |
The documentation and the explanation are pretty much self-explanatory:
http://docs.python.org/library/collections.html#collections.defaultdict
The type function(int/str etc.) passed as an argument is used to initialize a default value for any given key where the key is not present in the dict.
add a comment |
protected by Sheldore Jul 14 at 13:03
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
14 Answers
14
active
oldest
votes
14 Answers
14
active
oldest
votes
active
oldest
votes
active
oldest
votes
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
@Ambareeshd.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged.defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.
– Sven Marnach
May 2 at 19:10
add a comment |
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
@Ambareeshd.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged.defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.
– Sven Marnach
May 2 at 19:10
add a comment |
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
Usually, a Python dictionary throws a KeyError
if you try to get an item with a key that is not currently in the dictionary. The defaultdict
in contrast will simply create any items that you try to access (provided of course they do not exist yet). To create such a "default" item, it calls the function object that you pass to the constructor (more precisely, it's an arbitrary "callable" object, which includes function and type objects). For the first example, default items are created using int()
, which will return the integer object 0
. For the second example, default items are created using list()
, which returns a new empty list object.
edited Feb 10 at 14:35
answered May 5 '11 at 15:49
Sven MarnachSven Marnach
382k85 gold badges775 silver badges715 bronze badges
382k85 gold badges775 silver badges715 bronze badges
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
@Ambareeshd.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged.defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.
– Sven Marnach
May 2 at 19:10
add a comment |
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
@Ambareeshd.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged.defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.
– Sven Marnach
May 2 at 19:10
2
2
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
Is it functionally different than using d.get(key, default_val) ?
– Ambareesh
May 1 at 1:31
10
10
@Ambareesh
d.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged. defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.– Sven Marnach
May 2 at 19:10
@Ambareesh
d.get(key, default)
won't ever modify your dictionary – it will just return the default and leave the dictionary unchanged. defaultdict
, on the other hand, will insert a key into the dictionary if it isn't there yet. This is a big difference; see the examples in the question to understand why.– Sven Marnach
May 2 at 19:10
add a comment |
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict =
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned0
the integer, if it wassomeddict = defaultdict(list)
it returns[ ]
. Is 0 the default integer? Or [ ] the default list?
– Gathide
Jan 5 '17 at 7:30
Neither.0
is immutable - in CPython all values from-5
to256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time withint()
orlist()
. That way,d[k].append(v)
can work without filling the dictionary with references to the same list, which would renderdefaultdict
almost useless. If this were the behaviour,defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)
– wizzwizz4
Oct 7 '17 at 8:58
add a comment |
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict =
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned0
the integer, if it wassomeddict = defaultdict(list)
it returns[ ]
. Is 0 the default integer? Or [ ] the default list?
– Gathide
Jan 5 '17 at 7:30
Neither.0
is immutable - in CPython all values from-5
to256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time withint()
orlist()
. That way,d[k].append(v)
can work without filling the dictionary with references to the same list, which would renderdefaultdict
almost useless. If this were the behaviour,defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)
– wizzwizz4
Oct 7 '17 at 8:58
add a comment |
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict =
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict =
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
edited Dec 20 '15 at 14:36
kmario23
23.4k6 gold badges76 silver badges89 bronze badges
23.4k6 gold badges76 silver badges89 bronze badges
answered May 5 '11 at 15:48
orlporlp
70.7k27 gold badges166 silver badges250 bronze badges
70.7k27 gold badges166 silver badges250 bronze badges
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned0
the integer, if it wassomeddict = defaultdict(list)
it returns[ ]
. Is 0 the default integer? Or [ ] the default list?
– Gathide
Jan 5 '17 at 7:30
Neither.0
is immutable - in CPython all values from-5
to256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time withint()
orlist()
. That way,d[k].append(v)
can work without filling the dictionary with references to the same list, which would renderdefaultdict
almost useless. If this were the behaviour,defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)
– wizzwizz4
Oct 7 '17 at 8:58
add a comment |
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned0
the integer, if it wassomeddict = defaultdict(list)
it returns[ ]
. Is 0 the default integer? Or [ ] the default list?
– Gathide
Jan 5 '17 at 7:30
Neither.0
is immutable - in CPython all values from-5
to256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time withint()
orlist()
. That way,d[k].append(v)
can work without filling the dictionary with references to the same list, which would renderdefaultdict
almost useless. If this were the behaviour,defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)
– wizzwizz4
Oct 7 '17 at 8:58
9
9
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
"The type of this new pair is given by the argument of defaultdict." Note that the argument can be any callable object - not just type functions. For example if foo was a function that returned "bar", foo could be used as an argument to default dict and if a non-present key was accessed, its value would be set to "bar".
– lf215
Jul 29 '13 at 5:56
11
11
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Or if you just want to return "bar": somedict = defaultdict(lambda:"bar")
– Michael Scott Cuthbert
Jun 2 '14 at 21:23
Fourth line returned
0
the integer, if it was someddict = defaultdict(list)
it returns [ ]
. Is 0 the default integer? Or [ ] the default list?– Gathide
Jan 5 '17 at 7:30
Fourth line returned
0
the integer, if it was someddict = defaultdict(list)
it returns [ ]
. Is 0 the default integer? Or [ ] the default list?– Gathide
Jan 5 '17 at 7:30
Neither.
0
is immutable - in CPython all values from -5
to 256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time with int()
or list()
. That way, d[k].append(v)
can work without filling the dictionary with references to the same list, which would render defaultdict
almost useless. If this were the behaviour, defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)– wizzwizz4
Oct 7 '17 at 8:58
Neither.
0
is immutable - in CPython all values from -5
to 256
are cached singletons but this is implementation-specific behaviour - in both cases a new instance is "created" each time with int()
or list()
. That way, d[k].append(v)
can work without filling the dictionary with references to the same list, which would render defaultdict
almost useless. If this were the behaviour, defaultdict
would take a value, not a lambda, as a parameter. (Sorry for the terrible explanation!)– wizzwizz4
Oct 7 '17 at 8:58
add a comment |
defaultdict
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict
lets the caller specify the default(value to be returned) up front when the container is initialized."
as defined by Doug Hellmann in The Python Standard Library by Example
How to use defaultdict
Import defaultdict
>>> from collections import defaultdict
Initialize defaultdict
Initialize it by passing
callable as its first argument(mandatory)
>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
>>> def foo():
... return 'default value'
...
>>> d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, )
>>> d_list
defaultdict(<type 'list'>, )
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, )
**kwargs as its second argument(optional)
>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
or
>>> kwargs = 'a':10,'b':12,'c':13
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
How does it works
As is a child class of standard dictionary, it can perform all the same functions.
But in case of passing an unknown key it returns the default value instead of error. For ex:
>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12, 'd': 0)
In case you want to change default value overwrite default_factory:
>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0)
or
>>> def foo():
... return 2
>>> d_int.default_factory = foo
>>> d_int['f']
2
>>> d_int
defaultdict(<function foo at 0x7f34a0a0a140>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0, 'f': 2)
Examples in the Question
Example 1
As int has been passed as default_factory, any unknown key will return 0 by default.
Now as the string is passed in the loop, it will increase the count of those alphabets in d.
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> d.default_factory
<type 'int'>
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
>>> d
defaultdict(<type 'int'>, 'i': 4, 'p': 2, 's': 4, 'm': 1)
Example 2
As a list has been passed as default_factory, any unknown(non-existent) key will return [ ](ie. list) by default.
Now as the list of tuples is passed in the loop, it will append the value in the d[color]
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> d.default_factory
<type 'list'>
>>> for k, v in s:
... d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d
defaultdict(<type 'list'>, 'blue': [2, 4], 'red': [1], 'yellow': [1, 3])
add a comment |
defaultdict
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict
lets the caller specify the default(value to be returned) up front when the container is initialized."
as defined by Doug Hellmann in The Python Standard Library by Example
How to use defaultdict
Import defaultdict
>>> from collections import defaultdict
Initialize defaultdict
Initialize it by passing
callable as its first argument(mandatory)
>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
>>> def foo():
... return 'default value'
...
>>> d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, )
>>> d_list
defaultdict(<type 'list'>, )
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, )
**kwargs as its second argument(optional)
>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
or
>>> kwargs = 'a':10,'b':12,'c':13
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
How does it works
As is a child class of standard dictionary, it can perform all the same functions.
But in case of passing an unknown key it returns the default value instead of error. For ex:
>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12, 'd': 0)
In case you want to change default value overwrite default_factory:
>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0)
or
>>> def foo():
... return 2
>>> d_int.default_factory = foo
>>> d_int['f']
2
>>> d_int
defaultdict(<function foo at 0x7f34a0a0a140>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0, 'f': 2)
Examples in the Question
Example 1
As int has been passed as default_factory, any unknown key will return 0 by default.
Now as the string is passed in the loop, it will increase the count of those alphabets in d.
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> d.default_factory
<type 'int'>
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
>>> d
defaultdict(<type 'int'>, 'i': 4, 'p': 2, 's': 4, 'm': 1)
Example 2
As a list has been passed as default_factory, any unknown(non-existent) key will return [ ](ie. list) by default.
Now as the list of tuples is passed in the loop, it will append the value in the d[color]
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> d.default_factory
<type 'list'>
>>> for k, v in s:
... d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d
defaultdict(<type 'list'>, 'blue': [2, 4], 'red': [1], 'yellow': [1, 3])
add a comment |
defaultdict
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict
lets the caller specify the default(value to be returned) up front when the container is initialized."
as defined by Doug Hellmann in The Python Standard Library by Example
How to use defaultdict
Import defaultdict
>>> from collections import defaultdict
Initialize defaultdict
Initialize it by passing
callable as its first argument(mandatory)
>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
>>> def foo():
... return 'default value'
...
>>> d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, )
>>> d_list
defaultdict(<type 'list'>, )
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, )
**kwargs as its second argument(optional)
>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
or
>>> kwargs = 'a':10,'b':12,'c':13
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
How does it works
As is a child class of standard dictionary, it can perform all the same functions.
But in case of passing an unknown key it returns the default value instead of error. For ex:
>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12, 'd': 0)
In case you want to change default value overwrite default_factory:
>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0)
or
>>> def foo():
... return 2
>>> d_int.default_factory = foo
>>> d_int['f']
2
>>> d_int
defaultdict(<function foo at 0x7f34a0a0a140>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0, 'f': 2)
Examples in the Question
Example 1
As int has been passed as default_factory, any unknown key will return 0 by default.
Now as the string is passed in the loop, it will increase the count of those alphabets in d.
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> d.default_factory
<type 'int'>
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
>>> d
defaultdict(<type 'int'>, 'i': 4, 'p': 2, 's': 4, 'm': 1)
Example 2
As a list has been passed as default_factory, any unknown(non-existent) key will return [ ](ie. list) by default.
Now as the list of tuples is passed in the loop, it will append the value in the d[color]
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> d.default_factory
<type 'list'>
>>> for k, v in s:
... d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d
defaultdict(<type 'list'>, 'blue': [2, 4], 'red': [1], 'yellow': [1, 3])
defaultdict
"The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict
lets the caller specify the default(value to be returned) up front when the container is initialized."
as defined by Doug Hellmann in The Python Standard Library by Example
How to use defaultdict
Import defaultdict
>>> from collections import defaultdict
Initialize defaultdict
Initialize it by passing
callable as its first argument(mandatory)
>>> d_int = defaultdict(int)
>>> d_list = defaultdict(list)
>>> def foo():
... return 'default value'
...
>>> d_foo = defaultdict(foo)
>>> d_int
defaultdict(<type 'int'>, )
>>> d_list
defaultdict(<type 'list'>, )
>>> d_foo
defaultdict(<function foo at 0x7f34a0a69578>, )
**kwargs as its second argument(optional)
>>> d_int = defaultdict(int, a=10, b=12, c=13)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
or
>>> kwargs = 'a':10,'b':12,'c':13
>>> d_int = defaultdict(int, **kwargs)
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12)
How does it works
As is a child class of standard dictionary, it can perform all the same functions.
But in case of passing an unknown key it returns the default value instead of error. For ex:
>>> d_int['a']
10
>>> d_int['d']
0
>>> d_int
defaultdict(<type 'int'>, 'a': 10, 'c': 13, 'b': 12, 'd': 0)
In case you want to change default value overwrite default_factory:
>>> d_int.default_factory = lambda: 1
>>> d_int['e']
1
>>> d_int
defaultdict(<function <lambda> at 0x7f34a0a91578>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0)
or
>>> def foo():
... return 2
>>> d_int.default_factory = foo
>>> d_int['f']
2
>>> d_int
defaultdict(<function foo at 0x7f34a0a0a140>, 'a': 10, 'c': 13, 'b': 12, 'e': 1, 'd': 0, 'f': 2)
Examples in the Question
Example 1
As int has been passed as default_factory, any unknown key will return 0 by default.
Now as the string is passed in the loop, it will increase the count of those alphabets in d.
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> d.default_factory
<type 'int'>
>>> for k in s:
... d[k] += 1
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
>>> d
defaultdict(<type 'int'>, 'i': 4, 'p': 2, 's': 4, 'm': 1)
Example 2
As a list has been passed as default_factory, any unknown(non-existent) key will return [ ](ie. list) by default.
Now as the list of tuples is passed in the loop, it will append the value in the d[color]
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> d.default_factory
<type 'list'>
>>> for k, v in s:
... d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> d
defaultdict(<type 'list'>, 'blue': [2, 4], 'red': [1], 'yellow': [1, 3])
edited May 23 '17 at 11:54
Community♦
11 silver badge
11 silver badge
answered Mar 21 '15 at 4:58
Somendra JoshiSomendra Joshi
1,1936 silver badges9 bronze badges
1,1936 silver badges9 bronze badges
add a comment |
add a comment |
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
add a comment |
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
add a comment |
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
edited Aug 7 '14 at 20:41
mackwerk
1,0663 gold badges17 silver badges41 bronze badges
1,0663 gold badges17 silver badges41 bronze badges
answered Jun 9 '13 at 17:48
varagrawalvaragrawal
1,4782 gold badges18 silver badges30 bronze badges
1,4782 gold badges18 silver badges30 bronze badges
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
add a comment |
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
3
3
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
The author has a very interesting message on ludovf.net
– varagrawal
Apr 15 '14 at 5:59
add a comment |
Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.
It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations.
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.
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print(ice_cream['Sarah'])
>>>Chunky Monkey
print(ice_cream['Joe'])
>>>Vanilla
Here is another example on How using defaultdict, we can reduce complexity
from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
result = []
counts = defaultdict(int)
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))
In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.
add a comment |
Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.
It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations.
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.
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print(ice_cream['Sarah'])
>>>Chunky Monkey
print(ice_cream['Joe'])
>>>Vanilla
Here is another example on How using defaultdict, we can reduce complexity
from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
result = []
counts = defaultdict(int)
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))
In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.
add a comment |
Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.
It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations.
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.
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print(ice_cream['Sarah'])
>>>Chunky Monkey
print(ice_cream['Joe'])
>>>Vanilla
Here is another example on How using defaultdict, we can reduce complexity
from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
result = []
counts = defaultdict(int)
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))
In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.
Dictionaries are a convenient way to store data for later retrieval by name (key). Keys must be unique, immutable objects, and are typically strings. The values in a dictionary can be anything. For many applications, the values are simple types such as integers and strings.
It gets more interesting when the values in a dictionary are collections (lists, dicts, etc.) In this case, the value (an empty list or dict) must be initialized the first time a given key is used. While this is relatively easy to do manually, the defaultdict type automates and simplifies these kinds of operations.
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.
from collections import defaultdict
ice_cream = defaultdict(lambda: 'Vanilla')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print(ice_cream['Sarah'])
>>>Chunky Monkey
print(ice_cream['Joe'])
>>>Vanilla
Here is another example on How using defaultdict, we can reduce complexity
from collections import defaultdict
# Time complexity O(n^2)
def delete_nth_naive(array, n):
ans = []
for num in array:
if ans.count(num) < n:
ans.append(num)
return ans
# Time Complexity O(n), using hash tables.
def delete_nth(array,n):
result = []
counts = defaultdict(int)
for i in array:
if counts[i] < n:
result.append(i)
counts[i] += 1
return result
x = [1,2,3,1,2,1,2,3]
print(delete_nth(x, n=2))
print(delete_nth_naive(x, n=2))
In conclusion, whenever you need a dictionary, and each element’s value should start with a default value, use a defaultdict.
edited Aug 23 at 4:06
Parth S.
187 bronze badges
187 bronze badges
answered Apr 23 '18 at 12:14
dimensiondimension
5005 silver badges13 bronze badges
5005 silver badges13 bronze badges
add a comment |
add a comment |
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, )
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, )
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, 'a': 0)
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, )
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, 'a': 0)
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, )
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, 'a': 1)
>>>
add a comment |
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, )
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, )
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, 'a': 0)
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, )
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, 'a': 0)
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, )
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, 'a': 1)
>>>
add a comment |
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, )
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, )
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, 'a': 0)
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, )
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, 'a': 0)
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, )
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, 'a': 1)
>>>
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, )
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, )
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, 'a': 0)
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, )
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, 'a': 0)
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, )
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, 'a': 1)
>>>
edited May 23 '17 at 12:18
Community♦
11 silver badge
11 silver badge
answered Dec 1 '14 at 23:54
Jon CoombsJon Coombs
1,2211 gold badge16 silver badges22 bronze badges
1,2211 gold badge16 silver badges22 bronze badges
add a comment |
add a comment |
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
add a comment |
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
add a comment |
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
edited May 15 '17 at 16:47
Bahrom
3,62419 silver badges36 bronze badges
3,62419 silver badges36 bronze badges
answered Apr 18 '16 at 1:00
Edward FalkEdward Falk
7,4168 gold badges53 silver badges89 bronze badges
7,4168 gold badges53 silver badges89 bronze badges
add a comment |
add a comment |
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option)
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, 'eggs': 1, 'spam': 7)
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.
add a comment |
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option)
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, 'eggs': 1, 'spam': 7)
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.
add a comment |
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option)
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, 'eggs': 1, 'spam': 7)
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option)
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(<type 'int'>, 'eggs': 1, 'spam': 7)
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.
edited Aug 17 '17 at 8:49
answered Aug 17 '17 at 8:40
Swadhikar CSwadhikar C
1,33312 silver badges23 bronze badges
1,33312 silver badges23 bronze badges
add a comment |
add a comment |
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9)
import collections
d =
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
add a comment |
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9)
import collections
d =
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
add a comment |
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9)
import collections
d =
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
Without defaultdict
, you can probably assign new values to unseen keys but you cannot modify it. For example:
import collections
d = collections.defaultdict(int)
for i in range(10):
d[i] += i
print(d)
# Output: defaultdict(<class 'int'>, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9)
import collections
d =
for i in range(10):
d[i] += i
print(d)
# Output: Traceback (most recent call last): File "python", line 4, in <module> KeyError: 0
edited Dec 19 '17 at 18:44
answered Dec 19 '17 at 18:04
Ming LiuMing Liu
213 bronze badges
213 bronze badges
add a comment |
add a comment |
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Herelist
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of1
, you'd uselambda:1
which is obviously not a type.
– antoine-sac
Sep 5 '18 at 9:55
add a comment |
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Herelist
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of1
, you'd uselambda:1
which is obviously not a type.
– antoine-sac
Sep 5 '18 at 9:55
add a comment |
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.
For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
print i
This prints:
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
edited Mar 8 '18 at 17:59
alexander.polomodov
4,39013 gold badges29 silver badges37 bronze badges
4,39013 gold badges29 silver badges37 bronze badges
answered Mar 8 '18 at 17:36
saarthak joharisaarthak johari
393 bronze badges
393 bronze badges
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Herelist
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of1
, you'd uselambda:1
which is obviously not a type.
– antoine-sac
Sep 5 '18 at 9:55
add a comment |
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Herelist
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of1
, you'd uselambda:1
which is obviously not a type.
– antoine-sac
Sep 5 '18 at 9:55
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Here
list
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of 1
, you'd use lambda:1
which is obviously not a type.– antoine-sac
Sep 5 '18 at 9:55
"The value fields' data type is specified upon initialization": this is not correct. An element factory function is provided. Here
list
is the function to call to fill in a missing value, not the type of the objects to create. For example, to have a default value of 1
, you'd use lambda:1
which is obviously not a type.– antoine-sac
Sep 5 '18 at 9:55
add a comment |
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
add a comment |
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
add a comment |
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
Well, defaultdict can also raise keyerror in the following case:
from collections import defaultdict
d = defaultdict()
print(d[3]) #raises keyerror
Always remember to give argument to the defaultdict like defaultdict(int).
answered Feb 22 at 20:42
Shweta SharmaShweta Sharma
358 bronze badges
358 bronze badges
add a comment |
add a comment |
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
add a comment |
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
add a comment |
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
In short:
defaultdict(int)
- the argument int indicates that the values will be int type.
defaultdict(list)
- the argument list indicates that the values will be list type.
answered Mar 28 at 3:44
Shravan kpShravan kp
313 bronze badges
313 bronze badges
add a comment |
add a comment |
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, 'foo': 'bar')
foo => bar
bar => default value
add a comment |
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, 'foo': 'bar')
foo => bar
bar => default value
add a comment |
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, 'foo': 'bar')
foo => bar
bar => default value
The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.
$ python collections_defaultdict.py
d: defaultdict(<function default_factory at 0x100468c80>, 'foo': 'bar')
foo => bar
bar => default value
answered Dec 30 '14 at 14:05
user3818875
add a comment |
add a comment |
The documentation and the explanation are pretty much self-explanatory:
http://docs.python.org/library/collections.html#collections.defaultdict
The type function(int/str etc.) passed as an argument is used to initialize a default value for any given key where the key is not present in the dict.
add a comment |
The documentation and the explanation are pretty much self-explanatory:
http://docs.python.org/library/collections.html#collections.defaultdict
The type function(int/str etc.) passed as an argument is used to initialize a default value for any given key where the key is not present in the dict.
add a comment |
The documentation and the explanation are pretty much self-explanatory:
http://docs.python.org/library/collections.html#collections.defaultdict
The type function(int/str etc.) passed as an argument is used to initialize a default value for any given key where the key is not present in the dict.
The documentation and the explanation are pretty much self-explanatory:
http://docs.python.org/library/collections.html#collections.defaultdict
The type function(int/str etc.) passed as an argument is used to initialize a default value for any given key where the key is not present in the dict.
edited Jun 9 '14 at 18:09
Totem
5,3332 gold badges24 silver badges52 bronze badges
5,3332 gold badges24 silver badges52 bronze badges
answered May 5 '11 at 15:50
Andreas JungAndreas Jung
1
1
add a comment |
add a comment |
protected by Sheldore Jul 14 at 13:03
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
9
BTW, depending upon your use case, do not forget to freeze the defaultdict for read-only use by setting its
default_factory = None
after you've finished populating the defaultdict. See this question.– Acumenus
Oct 30 '16 at 5:54
See also: stackoverflow.com/questions/17215400/…
– dreftymac
Oct 10 '17 at 21:05