问题描述
我有一些像这样的代码...
self.write(
'''''
很多东西在这里有%(这些)的命名表达式
''''''
%vars(自我)
)
然后我想在dict vars(self)中添加一个项目,所以我尝试了:
vars(self)+ {''x '':''123'',''y'':''345''}
这不行,也许是因为没有人能决定应该发生什么
到dict中已经存在的键? (我会说抛出异常)。
我可以用上面的%字符串
操作的方式添加两个dicts吗?这是编写我自己的函数的另一种情况,还是已经存在了
内置(或类似)?
I have some code like this...
self.write(
''''''
lots of stuff here with %(these)s named expressions
''''''
% vars(self)
)
Then I wanted to add an item to the dict vars(self), so I tried :
vars(self)+{''x'':''123'',''y'':''345''}
This doesn''t work, perhaps because no one could decide what should happen
to keys which already exist in the dict? (I''d say throw an exception).
Can I add two dicts in a way which is not cumbersome to the above % string
operation? Is this another case of writing my own function, or does a
builtin (or similar) already exist for this?
推荐答案
你可以使用dict.update(但是,这有效,所以你会在实际的字符串%语句之外做
。
d = {" a":1," b":2}
d.update({''x'':'''123'',''y'':'''345''})
print"%(..)s%(..)d ..." %d
-
mackstann mack @ incise.org
那么,对于这个家伙,基甸还有什么呢?
为什么他不能还记得他的圣经吗?
You can use dict.update(), however, this works in place, so you''ll have
to do it outside of the actual string% statement.
d = {"a": 1, "b": 2}
d.update({''x'':''123'',''y'':''345''})
print "%(..)s %(..)d ..." % d
--
m a c k s t a n n mack @ incise.org http://incise.org
So, what''s with this guy Gideon, anyway?
And why can''t he ever remember his Bible?
combinedDict = aDict.copy()
combinedDict.update(anotherDict)
如果这很麻烦,不知道你会考虑什么
非繁琐。
-
Erik Max Francis&& &&
__美国加利福尼亚州圣何塞市&& 37 20 N 121 53 W&& & tSftDotIotE
/ \革命不会电视转播
\ __ / Public Enemy
combinedDict = aDict.copy()
combinedDict.update(anotherDict)
If that''s cumbersome, don''t really know what you''d consider
non-cumbersome.
--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ The revolution will not televised
\__/ Public Enemy
combinedDict = aDict.copy()
combinedDict.update(anotherDict)
如果这很麻烦,不知道你认为什么不麻烦。
combinedDict = aDict.copy()
combinedDict.update(anotherDict)
If that''s cumbersome, don''t really know what you''d consider
non-cumbersome.
不知道你是否在问,但是:
vars(self)+ {''x'':''123' ',''y'':''345''}
我会认为这不麻烦。 ;-)
我唯一的猜测是,为什么不存在是没有人决定怎么做
就像钥匙一样。使用现有,覆盖或抛出异常(我的偏好)。
Don''t really know if you''re asking, but :
vars(self)+{''x'':''123'',''y'':''345''}
I would consider that non-cumbersome. ;-)
My only guess why that doesn''t exist is that no one decided what to do on
like keys. Use existing, overwrite, or throw exception (my preference).
这篇关于添加两个dicts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!