简体   繁体   English

将值附加到python中的两个键defaultdict

[英]Appending values to two key defaultdict in python

From a text file, I am trying to append one following value as the value from the two previous values as the keys. 从文本文件,我试图附加一个后面的值作为前两个值的值作为键。 Here is mt code: 这是mt代码:

# this is a sample file. The output that I would like is ["apple","orange"]
lines = "This is apple. This is orange".split() 
d = defaultdict(list)
d[("This", "is")] = list
for i, tokens in enumerate(lines):
    if "This" == lines[i] and "is" == lines[i+1]:
        d[(lines[i], lines[i+1])].append([lines[i+2]])
print d[("This", "is")]

But I get the error as shown below: 但我得到的错误如下所示:

TypeError: `append() takes exactly one argument (0 given)` on `d[(lines[i], lines[i+1])].append([lines[i+2]])`

Could someone help ? 有人可以帮忙吗?

The following line assign list type itself, not a list instance. 以下行分配list类型本身,而不是list实例。

d[("This", "is")] = list

Above line should be replaced with: 上面的行应替换为:

d[("This", "is")] = list()

or 要么

d[("This", "is")] = []

or the line can be removed completely, because defaultdict will handle the case if there's no matching key in the dictionary. 或者可以完全删除该行,因为如果字典中没有匹配的键, defaultdict将处理该情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM