Union of dict objects in Python

This question already has an answer here:

  • How to merge two dictionaries in a single expression? 48 answers

  • This question provides an idiom. You use one of the dicts as keyword arguments to the dict() constructor:

    dict(y, **x)
    

    Duplicates are resolved in favor of the value in x ; for example

    dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'}
    

    你也可以使用dict的update方法

    a = {'a' : 0, 'b' : 1}
    b = {'c' : 2}
    
    a.update(b)
    print a
    

    Two dictionaries

    def union2(dict1, dict2):
        return dict(list(dict1.items()) + list(dict2.items()))
    

    n dictionaries

    def union(*dicts):
        return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))
    
    链接地址: http://www.djcxy.com/p/17558.html

    上一篇: 如何从Python中的两个字典构造一个字典?

    下一篇: Python中的dict对象的联合