压缩成字典时需要独立的对象 [英] Independent objects needed when zipping into dict
问题描述
我有一个物品清单:
my_list = ['first', 'second', 'third']
我需要将此项目转换为字典(以便我可以通过其名称访问每个元素),并将多个计数器与每个元素相关联:counter1,counter2,counter3.
I need to convert this items into a dictionary (so I can access each element by it's name), and associate multiple counters to each element: counter1, counter2, counter3.
所以我执行以下操作:
counter_dict = {'counter1': 0, 'counter2': 0, 'counter3': 0}
my_dict = dict(zip(mylist, [counter_dict]*len(mylist)))
通过这种方式,我可以获得嵌套字典
This way I obtain a nested dictionary
{
'first': {
'counter1': 0,
'counter2': 0,
'counter3': 0
},
'second': {
'counter1': 0,
'counter2': 0,
'counter3': 0
},
'third': {
'counter1': 0,
'counter2': 0,
'counter3': 0
}
}
这里的问题是每个计数器字典不是独立的,所以当我更新一个计数器时,所有计数器都将更新.
The problem here is that each counter dictionary is not independent, so when I update one counter, all of them are updated.
以下行不仅更新 counter2
的时间为 second
,而且还更新 counter2
的 first
和第三
The following line not only updates the counter2
of second
but also updates counter2
of first
and third
my_dict['second']['counter2'] += 1
{
'first': {
'counter1': 0,
'counter2': 1,
'counter3': 0
},
'second': {
'counter1': 0,
'counter2': 1,
'counter3': 0
},
'third': {
'counter1': 0,
'counter2': 1,
'counter3': 0
}
}
我知道通过执行 [counter_dict] * len(mylist)
,我将所有词典都指向一个词典.
I am aware that by doing [counter_dict]*len(mylist)
I am pointing all dictionaries to a single one.
问题是,如何才能实现创建独立词典所需要的功能?最后,我需要:
Question is, how can I achieve what I need creating independent dictionaries? At the end I need to:
- 将列表中的每个元素作为键访问
- 对于每个元素,我可以独立更新多个计数器
非常感谢
推荐答案
尝试以下方法:
my_dict = {k: counter_dict.copy() for k in my_list}
代替压缩值-足以遍历键并使用dict压缩将计数器复制到值.
Instead of zipping values - it's enough to iterate over keys and copy your counters to values using dict compression.
但是请注意,这仅适用于一级counter_dict.如果需要嵌套字典,请使用 copy
包中的 deepcopy
:
But note, that this will work only with one level counter_dict. If needed nested dictionary - use deepcopy
from copy
package:
from copy import deepcopy
my_dict = {k: deepcopy(counter_dict) for k in my_list}
另一种方法-使用来自 collections
的 defaultdict
,因此您甚至不需要创建带有预定义计数器的字典:
Another aproach - using defaultdict
from collections
, so you dont even need to create dictionary with predefined counters:
from collections import defaultdict
my_dict = {k: defaultdict(int) for k in my_list}
这篇关于压缩成字典时需要独立的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!