简体   繁体   中英

Meaning of defaultdict(lambda: defaultdict(dict))

Python中以下行的含义是什么?

x = defaultdict(lambda: defaultdict(dict))

Let's resolve it from the inside out. Firstly, dict is the dictionary type. Like other types, calling it creates an instance (also known as object) of that type. A defaultdict is a type that takes a callable parameter: something that, when called, produces an item to put in the dictionary. This happens when an entry is accessed that was not present, instead of producing a KeyError like an ordinary dict . Thirdly, lambda is a way to create unnamed functions based on a single expression, so these two are similar (the second holds a function that knows its own name, the first doesn't):

y = lambda: defaultdict(dict)

def y():
    return defaultdict(dict)

And finally the whole thing is wrapped in another defaultdict . So the result is that x is a defaultdict that produces defaultdict s that produce dict instances. At the third level there aren't defaults anymore.

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