简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM