defaultdict is not defined

Question:

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?

Asked By: jason

||

Answers:

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

It might behoove you to read about the import statement.

Answered By: arshajii

You’re not importing defaultdict. Do either:

from collections import defaultdict

or

import collections
d = collections.defaultdict(list)
Answered By: Marcin

You need to write:

from collections import defaultdict
Answered By: peascloud

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

Answered By: Simran Makandar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.