[英]Function to create dictionary with default values that can be either immutable or mutable
I have a function to create a dictionary with specific keys, which accepts a parameter to specify what each key's "default" value should be. 我有一个用特定键创建字典的函数,该函数接受一个参数来指定每个键的“默认”值。
def new_dict(entrys_default=0):
my_dict = {}
for k in ['a', 'b', 'c']:
my_dict[k] = entrys_default
return my_dict
The issue is that when I call it with new_dict(entrys_default=[])
so that each entry in the dictionary is created with a new empty list as its value, when I then update one entry with returned_dict['a'].append(123)
then all entries are updated: 问题是,当我使用
new_dict(entrys_default=[])
调用时,将创建一个新的空列表作为其值来创建字典中的每个条目,然后再使用new_dict(entrys_default=[])
returned_dict['a'].append(123)
然后更新所有条目:
{'a': [123], 'b': [123], 'c': [123]}
This doesn't happen when using an integer, and I understand that it is because the entrys_default
is immutable when it is an integer, but is a reference to the same list when it is a list or dictionary. 使用整数时不会发生这种情况,我知道这是因为
entrys_default
是整数时是不可变的,但是当它是列表或字典时是对同一列表的引用。
I want to be able to have this function work the same as it does for integer parameters with lists and dictionaries as entrys_default
- ie each entry has its own list/dictionary - but want to keep the function flexible to also work for integers. 我希望能够使此函数的工作方式与对带有lists和
entrys_default
列表和字典的整数参数entrys_default
(即,每个条目都有自己的列表/字典),但希望保持该函数的灵活性,使其也适用于整数。
Can anyone please suggest the best way to go about this? 谁能建议最好的方法吗?
Do what collections.defaultdict
does; 做
collections.defaultdict
工作; instead of taking an "example" default value, take a function that returns the desired default value. 而不是采用“示例”默认值,而是采用返回所需默认值的函数。 Then call that function and use its return value to initialize each element of the
dict
being constructed. 然后调用该函数并使用其返回值初始化正在构建的
dict
每个元素。
def new_dict(make_default=int): # int() == 0
my_dict = {}
for k in ['a', 'b', 'c']:
my_dict[k] = make_default()
return my_dict
d = new_dict(list) # list() == [], but a distinct list each time it is called
d['a'].append(123)
assert d['a'] != d['b']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.