Python - 组合两个字典,连接字符串值? [英] Python - Combine two dictionaries, concatenate string values?

查看:196
本文介绍了Python - 组合两个字典,连接字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关:是否有任何pythonic方法来组合两个dicts(添加两个键出现的值)?



我想合并两个字符串:字符串字典,并连接值。上面的帖子建议使用 collections.Counter ,但它不处理字符串连接。

 >>>从集合导入计数器
>>>> a = Counter({'foo':'bar','baz':'bazbaz'})
>>> b = Counter({'foo':'baz'})
>>> a + b
追溯(最近的最后一次呼叫):
文件< stdin>,第1行,< module>
文件/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py,第569行,__add__
TypeError:不能连接str和 int'对象

(我的猜测是尝试设置 b ['baz '] to 0。)



我想获得 {'foo':'barbaz ','baz':'bazbaz'} 。连接顺序与我无关。什么是干净的,Pythonic的方法?

解决方案

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 key}
{'foo':'barbaz','baz':'bazbaz'}

对于Python 2.6及更早版本:

 >>>对于键中的k,可以使用(k,d.get(k,'')+ d1.get(k,''))
{'foo':'barbaz','baz':'bazbaz' }

这将适用于任何数量的数字:


$ b $





返回{k:.join(dic。 get(k,'')for dic in dictions)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'}
pre>

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

解决方案

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

这篇关于Python - 组合两个字典,连接字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆