领域理解:
>>> 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'}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)