2013-07-11 130 views
6

相關: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的方式來做到這一點?

+0

如果第二個字典看起來如此,預期的輸出是什麼:'{'foo':'baz','spam':'eggs'}'? –

+0

@AshwiniChaudhary {'foo':'barbaz','baz':'bazbaz','spam':'eggs'} – jbreed

回答

14

快譯通-理解:

>>> d = {'foo': 'bar', 'baz': 'bazbaz'} 
>>> d1 = {'foo': 'baz'} 
>>> keys = d.viewkeys() | d1.viewkeys() 
>>> {k : d.get(k, '') + d1.get(k, '') for k in keys} 
{'foo': 'barbaz', 'baz': 'bazbaz'} 

對於Python 2.6和更早的版本:

>>> dict((k, d.get(k, '') + d1.get(k, '')) for k in keys) 
{'foo': 'barbaz', 'baz': 'bazbaz'} 

這適用於任何數量的類型的字典的工作:

def func(*dicts): 
    keys = set().union(*dicts) 
    return {k: "".join(dic.get(k, '') for dic in dicts) for k in keys} 
... 
>>> d = {'foo': 'bar', 'baz': 'bazbaz'} 
>>> d1 = {'foo': 'baz','spam': 'eggs'} 
>>> d2 = {'foo': 'foofoo', 'spam': 'bar'} 
>>> func(d, d1, d2) 
{'foo': 'barbazfoofoo', 'baz': 'bazbaz', 'spam': 'eggsbar'} 
+0

字典理解,這是我聽到的第一個,但聽起來真棒! – 2013-07-11 23:56:47

0

可以寫一個通用的幫手,如:

a = {'foo':'bar', 'baz':'bazbaz'} 
b = {'foo':'baz'} 

def concatd(*dicts): 
    if not dicts: 
     return {} # or should this be None or an exception? 
    fst = dicts[0] 
    return {k: ''.join(d.get(k, '') for d in dicts) for k in fst} 

print concatd(a, b) 
# {'foo': 'barbaz', 'baz': 'bazbaz'} 

c = {'foo': '**not more foo!**'} 
print concatd(a, b, c) 
# {'foo': 'barbaz**not more foo!**', 'baz': 'bazbaz'}