简体   繁体   中英

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:

# 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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