user3358669 user3358669 - 1 month ago 16
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():
dict[A].append(B)
dict[B].append(A)
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

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()
[]
>>>