相關: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