Python defaultdict and lambda

后端 未结 5 624
野的像风
野的像风 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:24

    You are correct for what the first one does. As for y, it will create a defaultdict with default 0 when a key doesn't exist in y, so you can think of this as a nested dictionary. Consider the following example:

    y = defaultdict(lambda: defaultdict(lambda: 0))
    print y['k1']['k2']   # 0
    print dict(y['k1'])   # {'k2': 0}
    

    To create an equivalent nested dictionary structure without defaultdict you would need to create an inner dict for y['k1'] and then set y['k1']['k2'] to 0, but defaultdict does all of this behind the scenes when it encounters keys it hasn't seen:

    y = {}
    y['k1'] = {}
    y['k1']['k2'] = 0
    

    The following function may help for playing around with this on an interpreter to better your understanding:

    def to_dict(d):
        if isinstance(d, defaultdict):
            return dict((k, to_dict(v)) for k, v in d.items())
        return d
    

    This will return the dict equivalent of a nested defaultdict, which is a lot easier to read, for example:

    >>> y = defaultdict(lambda: defaultdict(lambda: 0))
    >>> y['a']['b'] = 5
    >>> y
    defaultdict( at 0xb7ea93e4>, {'a': defaultdict( at 0xb7ea9374>, {'b': 5})})
    >>> to_dict(y)
    {'a': {'b': 5}}
    

提交回复
热议问题