codepk
codepk

Reputation: 615

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)

Upvotes: 1

Views: 979

Answers (1)

Kijewski
Kijewski

Reputation: 26022

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

Upvotes: 4

Related Questions