[英]Function to create dictionary with default values that can be either immutable or mutable
我有一个用特定键创建字典的函数,该函数接受一个参数来指定每个键的“默认”值。
def new_dict(entrys_default=0):
my_dict = {}
for k in ['a', 'b', 'c']:
my_dict[k] = entrys_default
return my_dict
问题是,当我使用new_dict(entrys_default=[])
调用时,将创建一个新的空列表作为其值来创建字典中的每个条目,然后再使用new_dict(entrys_default=[])
returned_dict['a'].append(123)
然后更新所有条目:
{'a': [123], 'b': [123], 'c': [123]}
使用整数时不会发生这种情况,我知道这是因为entrys_default
是整数时是不可变的,但是当它是列表或字典时是对同一列表的引用。
我希望能够使此函数的工作方式与对带有lists和entrys_default
列表和字典的整数参数entrys_default
(即,每个条目都有自己的列表/字典),但希望保持该函数的灵活性,使其也适用于整数。
谁能建议最好的方法吗?
做collections.defaultdict
工作; 而不是采用“示例”默认值,而是采用返回所需默认值的函数。 然后调用该函数并使用其返回值初始化正在构建的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.