gpt4 book ai didi

python - 合并两个字典,连接字符串值?

转载 作者:太空狗 更新时间:2023-10-29 21:22:30 24 4
gpt4 key购买 nike

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

我想合并两个 string:string 字典,并连接值。上面的帖子推荐使用 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

(我的猜测是 Counter 试图将 b['baz'] 设置为 0。)

我想得到 {'foo':'barbaz', 'baz':'bazbaz'} 的结果。连接顺序对我来说并不重要。执行此操作的干净、Pythonic 方式是什么?

最佳答案

字典理解:

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

关于python - 合并两个字典,连接字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17604837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com