Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

python - Combine two dictionaries, concatenate string values?

Related: Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

I'd like to merge two string:string dictionaries, and concatenate the values. The above post recommends using collections.Counter, but it doesn't handle string concatenation.

>>> 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

(My guess is Counter tries to set b['baz'] to 0.)

I'd like to get a result of {'foo':'barbaz', 'baz':'bazbaz'}. Concatenation order doesn't matter to me. What is a clean, Pythonic way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dict-comprehension:

>>> 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'}

For Python 2.6 and earlier:

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

This will work for any number of dicts:

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'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...