TypeError: first argument must be callable

♀尐吖头ヾ 提交于 2020-04-12 07:59:13

问题


fs = codecs.open('grammar_new.txt', encoding='utf-8')
unidata=[]
d={}
fr=codecs.open('rule.txt', 'w')
for line in fs:
    line_data=line.split()
    for i in range(0,len(line_data)):
       unidata.append(line_data[i])


d = defaultdict(unidata)

while executing this code will generate error as d = defaultdict(unidata) TypeError: first argument must be callable..I want to store duplicate keys in dictionary


回答1:


The first argument to defaultdict must be callable. You've passed an instance of list which isn't callable. You want to pass the 'list' type instead.

Typical use would be something like:

d = defaultdict(list)
for k, v in something:
    d[k].append(v)

Based on the unidata you seem to have provided in your comment, I think you want:

>>> from collections import defaultdict
>>> unidata = [[u'NP--->', u'N_NNP'], [u'NP--->', u'N_NN_S_NU'], [u'NP--->', u'N_NNP'], [u'NP--->', u'N_NNP'], [u'VGF--->', u'V_VM_VF'], [u'NP--->', u'N_NN']]
>>> d = defaultdict(list)
>>> for k, v in unidata:
...     d[k].append(v)
... 
>>> d
defaultdict(<type 'list'>, {u'VGF--->': [u'V_VM_VF'], u'NP--->': [u'N_NNP', u'N_NN_S_NU', u'N_NNP', u'N_NNP', u'N_NN']})



回答2:


I want to store duplicate keys in dictionary

This is simply not possible. Keys in dictionaries are unique. I think what you want is this:

d = defaultdict(list)
with codecs.open('grammar_new.txt', encoding='utf-8') as f:
   for line in f:
      if len(line.rstrip()):
          key,value = line.rstrip().split()
          d[key].append(value)

print(d)

Now d will contain for each key a list that contains the corresponding values. Each key must be unique, but it can have any number of values, which can be duplicates.



来源:https://stackoverflow.com/questions/21422670/typeerror-first-argument-must-be-callable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!