迷茫2017-04-18 10:16:44
>>> d = {}
>>> help(d.fromkeys)
Help on built-in function fromkeys:
fromkeys(...)
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
The values of all 5 elements are v, and as v is a complex type, it is passed by reference instead of value.
巴扎黑2017-04-18 10:16:44
Because []
只会被初始化一次,然后所有的key都会引用到它,也就是浅拷贝
, it can be implemented in another way:
First way:
in python3
d = {i: [] for i in range(5)}
d[1].append({'k': 'v'})
The second type:
from collections import defaultdict
d = defaultdict(list)
d[1].append({'k': 'v'})
copy.deepcopy
I don’t really want to use it anymore