结合两个字典,连接字符串值?

结合两个字典,连接字符串值?,第1张

结合两个字典,连接字符串值?

领域理解

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5655242.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存