Using python 3.2.
import collections d = defaultdict(int)
run
NameError: name 'defaultdict' is not defined
Ive restarted Idle. I know collections is being imported, because typing
collections
results in
<module 'collections' from '/usr/lib/python3.2/collections.py'>
also help(collections) shows me the help including the defaultdict class.
What am I doing wrong?
A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError .
The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries.
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.
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.
>>> import collections >>> d = collections.defaultdict(int) >>> d defaultdict(<type 'int'>, {})
It might behoove you to read about the import
statement.
You're not importing defaultdict
. Do either:
from collections import defaultdict
or
import collections d = collections.defaultdict(list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With