Search code examples
pythonpython-2.7dictionarylambdadefaultdict

How to use defaultdict to create a dictionary with a lambda function?


I am trying to create a dictionary with a lambda function which can conditionally insert a value based on the 2nd term in the key.

Example:
wts = defaultdict(lambda x: if x[1] == somevalue then 1 else 0)

Solution

  • A conditional expression in Python looks like:

    then_expr if condition else else_expr
    

    In your example:

    wts = defaultdict(lambda x: 1 if x[1] == somevalue else 0)
    

    As khelwood pointed out in the comments, the factory function for a defaultdict does not take arguments. You have to override dict.__missing__ directly:

    class WTS(dict):
        def __missing__(self, key):
            return 1 if key[1] == somevalue else 0
    
    wts = WTS()
    

    Or more readable:

    class WTS(dict):
        def __missing__(self, key):
            if key[1] == somevalue:
                return 1
            else:
                return 0