user3358669 user3358669 - 1 year ago 232
Python Question

TypeError: deafultdict must have first arguments callable

def parse_neighbors(neighbors, vars):
"""Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
regions to neighbors. The syntax is a region name followed by a ':'
followed by zero or more region names, followed by ';', repeated for
each region name. If you say 'X: Y' you don't need 'Y: X'.
>>> parse_neighbors('X: Y Z; Y: Z')
{'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']}
dict = defaultdict([])
for var in vars:
dict[var] = []
specs = [spec.split(':') for spec in neighbors.split(';')]
for (A, Aneighbors) in specs:
A = A.strip();
dict.setdefault(A, [])
for B in Aneighbors.split():
return dict

When I am calling this snippet from AIMA book, like below:

neigh = parse_neighbors(constr, vars)

where constr is a String and vars is a neighbour,

I am getting below error:
dict = defaultdict([])
TypeError: first argument must be callable

Please help!!!

Answer Source

You need to use:

d = defaultdict(list)

Instead of:

d = defaultdict([])

As the error message says:

TypeError: first argument must be callable

[] is not a callable, it is an empty list.

>>> []()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

list is a callable. Note what happens when you call it:

>>> list()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download