I am trying to understand the following code:
from collections import defaultdict
dd_pair = defaultdict(lambda: [0, 0])
dd_pair[2][1] = 1 # now dd_pair contains {2: [0,1]}
I understand defaultdict
defaults to a list of two elements here. But how is the result ending up to be {2: [0,1]}
dd_pair[2]
is returning a reference to a freshly created list
with the value [0, 0]
. Ignore the defaultdict
itself, and see how it works with a list
like that:
>>> mylist = [0, 0]
>>> mylist[1] = 1
>>> mylist
[0, 1]
The defaultdict
is just dynamically creating a list
like mylist
each time you access a heretofore unaccessed key, storing it as the value of the requested key, and returning a reference to it. By adding [1]
you do an index assignment to that list
, and since it's the same list
reference that was stored and returned, modifying one modifies the other.
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.