Defaultdict got TypeError: first argument must be callable or None

Hello again to all…sorry for so many questions…I have this script below. Am using jupyter notebook…it is always like this…when i first run, all is fine…but when 2nd run it shows error…pls help check…thanks

the code

###Duplicate @ Y
from collections import defaultdict
import pandas as pd


df = pd.DataFrame(
    [
        (76, 44),
        (32, 45),
        (77, 44),
        (78, 44),
        (78, 34),
        (78, 45),
        (45, 44),
        (87, 54),
        (34, 23),
        (76, 45),
        (54, 58),
        (95, 34),
        (77, 45),
        (84, 45),
    ], columns=('Y', 'X')
)

entries = defaultdict(list)

for x, y in zip(df.loc[ : , 'X'], df.loc[ : , 'Y']):
    entries[x].append(y)

#print('X\tY')

for x, y_list in entries.items():
    y_list.sort()

    for start in range(len(y_list) - 2):
        if y_list[start] == y_list[start + 1] - 1 == y_list[start + 2] - 2:
            for y in y_list[start : start + 3]:
                test = (f'{y}\t{x}')
                print(test)

on second run the error shows below.

TypeError                                 Traceback (most recent call last)
Cell In[3], line 25
      3 import pandas as pd
      6 df = pd.DataFrame(
      7     [
      8         (76, 44),
   (...)
     22     ], columns=('Y', 'X')
     23 )
---> 25 entries = defaultdict(list)
     27 for x, y in zip(df.loc[ : , 'X'], df.loc[ : , 'Y']):
     28     entries[x].append(y)

TypeError: first argument must be callable or None

Hoping for any support…thanks

Hello again to all…sorry for so many questions…I have this script
below. Am using jupyter notebook…it is always like this…when i
first run, all is fine…but when 2nd run it shows error…pls help
check…thanks

My recollection is that a Jupyter notebook keeps the state around, so
variables have the values derived from running your programme, when you
run it a second time?

the code
[…]

Are you sure this is exactly the code giving the error? I ask because
of a speculation about the cause. You’re TypeError arises from this
line:

 ---> 25 entries = defaultdict(list)

That suggests to me that when you ran this the second time the name
list no longer refers the Python’s list type, but to something else.
Try printing it:

 print("list =", list)

The reason I’m speculating this way is two fold:

  • defaultdict expects a callable as the factory function for new key
    values, so that implies that the value of list is no longer a
    callable value
  • you’ve got the variable name y_list in use; might this not always
    have been named this way? Might you have used plain old list instead
    at some point?

Anyway, the most direct thing to do is to print(list) just before
the list which raises the error; maybe it isn’t what you expect.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like