Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict is not defined

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?

like image 654
jason Avatar asked Jul 20 '13 21:07

jason


People also ask

How do you declare a Defaultdict?

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 .

What is Defaultdict in Python?

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.

What does Defaultdict mean?

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.

How does Defaultdict in Python 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.


2 Answers

>>> import collections >>> d = collections.defaultdict(int) >>> d defaultdict(<type 'int'>, {}) 

It might behoove you to read about the import statement.

like image 178
arshajii Avatar answered Sep 18 '22 13:09

arshajii


You're not importing defaultdict. Do either:

from collections import defaultdict 

or

import collections d = collections.defaultdict(list) 
like image 21
Marcin Avatar answered Sep 20 '22 13:09

Marcin