【发布时间】:2013-07-10 09:37:57
【问题描述】:
相关:Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
我想合并两个 string:string 字典,并连接这些值。上面的帖子推荐使用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
(我的猜测是 Counter 尝试将 b['baz'] 设置为 0。)
我想得到{'foo':'barbaz', 'baz':'bazbaz'} 的结果。串联顺序对我来说并不重要。什么是干净的 Pythonic 方式来做到这一点?
【问题讨论】:
-
如果第二个字典看起来像:
{'foo':'baz','spam':'eggs'}? -
@AshwiniChaudhary {'foo':'barbaz', 'baz':'bazbaz', 'spam':'eggs'}
标签: python string dictionary