Combine two dictionaries, concatenate string values?

前端 未结 3 1556
感情败类
感情败类 2020-12-15 01:45

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 concaten

3条回答
  •  隐瞒了意图╮
    2020-12-15 02:15

    One can use defaultdict to achieve this:

    from collections import defaultdict
    
    a = {'foo': 'bar', 'baz': 'bazbaz'}
    b = {'foo': 'baz'}
    
    new_dict = defaultdict(str)
    for key, value in a.items():
        new_dict[key] += value
    for key, value in b.items():
        new_dict[key] += value
    
    print(new_dict)
    # defaultdict(, {'foo': 'barbaz', 'baz': 'bazbaz'})
    print(dict(new_dict))
    # {'foo': 'barbaz', 'baz': 'bazbaz'}
    

    If there are many dicts to join, we could use itertools.chain.from_iterable:

    from collections import defaultdict
    from itertools import chain
    
    a = {'foo': 'bar', 'baz': 'bazbaz'}
    b = {'foo': 'baz'}
    c = {'baz': '123'}
    dicts = [a, b, c]
    
    new_dict = defaultdict(str)
    for key, value in chain.from_iterable(map(dict.items, dicts)):
        new_dict[key] += value
    
    print(dict(new_dict))
    # {'foo': 'barbaz', 'baz': 'bazbaz123'}
    

提交回复
热议问题