Search code examples
pythonlistdefaultdict

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 ?


Solution

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