有没有办法使用另一个dict在Python dict上设置多个默认值? [英] Is there a way to set multiple defaults on a Python dict using another dict?
问题描述
mydict = {'a':0}
defaults = {
'a':5,
'b':10,
'c':15
}
我想要使用<$ c $的默认值来扩展 mydict
c> defaults ,这样a保持不变,但是填写了b和c。我知道 dict.setdefault()
和 dict.update()
,但每个只做一半想要使用 dict.setdefault()
,我必须循环使用 defaults
中的每个变量;但是使用 dict.update()
, defaults
将会消除中的任何预先存在的值mydict
。
有没有一些功能,我没有发现内置到Python可以做到这一点?如果没有,是否有更多的Pythonic方式编写循环来重复调用 dict.setdefaults()
而不是这样:
$ b mydict.setdefault(key,defaults [key])
上下文:我正在Python中编写一些控制如何解析XML树的数据。每个节点都有一个dict(即如何处理每个节点),而我宁愿写出的数据是稀疏的,而是用默认值填充。示例代码只是一个例子...实际代码在默认dict中有更多的键/值对。
(我意识到这个整个问题只是一个小问题,但是它一直困扰着我,所以我想知道是否有更好的方法来做到这一点,我不知道。)
你不能让mydict成为默认的副本,这样,mydict将会有所有正确的值开始?
mydict = default.copy()
Suppose I've got two dicts in Python:
mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
I want to be able to expand mydict
using the default values from defaults
, such that 'a' remains the same but 'b' and 'c' are filled in. I know about dict.setdefault()
and dict.update()
, but each only do half of what I want - with dict.setdefault()
, I have to loop over each variable in defaults
; but with dict.update()
, defaults
will blow away any pre-existing values in mydict
.
Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call dict.setdefaults()
than this:
for key in defaults.keys():
mydict.setdefault(key, defaults[key])
Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.
(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)
Couldnt you make mydict be a copy of default, That way, mydict would have all the correct values to start with?
mydict = default.copy()
这篇关于有没有办法使用另一个dict在Python dict上设置多个默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!