相关:Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?Python - 合并两个字典,连接字符串值?
我想合并两个字符串:字符串字典,并连接值。以上帖子建议使用collections.Counter
,但它不处理字符串连接。
>>> from collections import Counter
>>> a = Counter({'foo':'bar', 'baz':'bazbaz'})
>>> b = Counter({'foo':'baz'})
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 569, in __add__
TypeError: cannot concatenate 'str' and 'int' objects
(我的猜测是柜台尝试设置b['baz']
0)
我想获得的{'foo':'barbaz', 'baz':'bazbaz'}
结果。连接顺序对我无关紧要。什么是干净的,Pythonic的方式来做到这一点?
如果第二个字典看起来如此,预期的输出是什么:'{'foo':'baz','spam':'eggs'}'? –
@AshwiniChaudhary {'foo':'barbaz','baz':'bazbaz','spam':'eggs'} – jbreed