Python defaultdict and lambda

后端 未结 5 609
野的像风
野的像风 2020-12-02 05:31

In someone else\'s code I read the following two lines:

x = defaultdict(lambda: 0)
y = defaultdict(lambda: defaultdict(lambda: 0))

As the a

5条回答
  •  渐次进展
    2020-12-02 06:15

    All answers are good enough still I am giving the answer to add more info:

    "defaultdict requires an argument that is callable. That return result of that callable object is the default value that the dictionary returns when you try to access the dictionary with a key that does not exist."

    Here's an example

    SAMPLE= {'Age':28, 'Salary':2000}
    SAMPLE = defaultdict(lambda:0,SAMPLE)
    
    >>> SAMPLE
    defaultdict( at 0x0000000002BF7C88>, {'Salary': 2000, 'Age': 28})
    
    >>> SAMPLE['Age']----> This will return 28
    >>> SAMPLE['Phone']----> This will return 0   # you got 0 as output for a non existing key inside SAMPLE
    

提交回复
热议问题