Combine two dictionaries, concatenate string values?

前端 未结 3 1560
感情败类
感情败类 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:16

    Can write a generic helper, such as:

    a = {'foo':'bar', 'baz':'bazbaz'}
    b = {'foo':'baz'}
    
    def concatd(*dicts):
        if not dicts:
            return {} # or should this be None or an exception?
        fst = dicts[0]
        return {k: ''.join(d.get(k, '') for d in dicts) for k in fst}
    
    print concatd(a, b)
    # {'foo': 'barbaz', 'baz': 'bazbaz'}
    
    c = {'foo': '**not more foo!**'}
    print concatd(a, b, c)
    # {'foo': 'barbaz**not more foo!**', 'baz': 'bazbaz'}
    

提交回复
热议问题