defaultdict is not defined

Each Answer to this Q is separated by one/two green lines.

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?

>>> 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)

You need to write:

from collections import defaultdict

Defaultdict is a container like dictionaries present in the module collections. To access defaultdict you would either have to modify your import statement to –

from collections import defaultdict

or use –

import collections
d = collections.defaultdict(int)

to be able to use defaultdict


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .