结合两个字典,连接字符串值? [英] Combine two dictionaries, concatenate string values?
本文介绍了结合两个字典,连接字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
相关:我想合并两个string:string字典,并连接值.上面的文章建议使用collections.Counter
,但它不处理字符串连接.
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
(我的猜测是Counter尝试将b['baz']
设置为0.)
(My guess is Counter tries to set b['baz']
to 0.)
我想得到{'foo':'barbaz', 'baz':'bazbaz'}
的结果.串联顺序对我来说无关紧要.什么是干净的Pythonic方法?
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?
推荐答案
词典理解:
>>> 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和更早版本:
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'}
这篇关于结合两个字典,连接字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文