Lambda parameter function in python
Question: I am supposed to analyze shakespeare text using NLTK ( sentiment analysis)
using python 3.4. But I get this error message:

    
    
    **Traceback (most recent call last):
      File "C:\Users\HAMIMOUNE\AppData\Roaming\nltk_data\shakespeare.py", line 8, in <module>
        [ line.split('\t') for line in open("AFINN-96.txt") ]))
    TypeError: <lambda>() missing 1 required positional argument: 'v'**
    

here is my code:

    
    
    from nltk.corpus import shakespeare
    from collections import defaultdict
    import json
    hamlet = shakespeare.xml('hamlet.xml')
    speeches = hamlet.findall('.//SPEECH')
    prevSpeaker =  speeches[0].find('SPEAKER').text
    afinn = dict(map(lambda k,v: (k,int(v)), 
                    [ line.split('\t') for line in open("AFINN-96.txt") ])) 
    
    dict = defaultdict(lambda: defaultdict(lambda: 0))
    for speech in speeches:
        speaker = speech.find('SPEAKER').text
        lines = "\n".join(line.text for line in speech.findall('LINE') if line.text is not None)
        sentiment = sum(map(lambda word: afinn.get(word, 0), lines.lower().split()))
        dict[speaker][prevSpeaker] += sentiment
        prevSpeaker = speaker
    print(json.dumps(dict, sort_keys=True, indent=4))
    


Answer: The [`map`](https://docs.python.org/3/library/functions.html#map) calls the
function with an argument (a list of strings in this case). You need to adjust
the `lambda` to take a parameter:

    
    
    afinn = dict(map(lambda item: (item[0], int(item[1])), 
                     [ line.split('\t') for line in open("AFINN-96.txt") ])) 
    

Alternative using dict-comprehension:

    
    
    afinn = {k: int(v) for k, v in
             [line.split('\t') for line in open("AFINN-96.txt")]}
    

BTW, don't use `dict` as a variable name. Overwriting it prevent you to use a
builtin function/type
[`dict`](https://docs.python.org/2/library/functions.html#func-dict).

