[英]TypeError: first argument must be callable
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 在执行此代码时将生成错误,因为d = defaultdict(unidata)TypeError:第一个参数必须可调用。我想在字典中存储重复的键
The first argument to defaultdict
must be callable . defaultdict
的第一个参数必须是callable 。 You've passed an instance of list
which isn't callable. 您已传递了一个不可调用的list
实例。 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: 根据您似乎在评论中提供的unidata
,我认为您想要:
>>> 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']})
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. 现在d
将为每个键包含一个包含相应值的列表。 Each key must be unique, but it can have any number of values, which can be duplicates. 每个键都必须是唯一的,但是可以有任意多个值,可以重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.