我对python和字典有问题。我有一个名为dirs的列表,它包含所有目录名。我想要生成类似于下面的
dirs_count = {'placements':{'total':0,'Others':0},'x-force':{'total':0,'Others':0})我使用了下面的代码来生成这个代码。
dirs = ['placemetns', 'x-code']
dirs_count = dict(zip(dirs,[{'total':0, 'others': 0}]*len(dirs)))
# {'placements':{'total':0,'others':0},'x-code':{'total':0,'others':0}}但这里的问题是,如果我修改一个字典值,就会发生以下情况。
dirs_count['placements']['total'] = 5
# {'placements':{'total':5,'others':0},'x-code':{'total':5,'others':0}}有什么办法可以防止这种情况吗?
或
是否有任何方法生成不影响修改时的实体字典的dirs_count?
发布于 2016-02-18 16:19:42
之所以会发生这种情况,是因为[{'total':0, 'others': 0}]*len(dirs)为您提供了许多对同一个dict的引用,因此对一个dict的任何更改都会影响所有副本。试一试
dirs = ['placemetns', 'x-code']
dicts = [{'total':0, 'others': 0} for i in dirs]
dirs_count = dict(zip(dirs,dicts))https://stackoverflow.com/questions/35486606
复制相似问题