Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 468
pythonlearner Avatar asked May 24 '26 11:05

pythonlearner


1 Answers

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.

like image 105
falsetru Avatar answered May 27 '26 00:05

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!