pythondictionaryassociative-arrayidiomsset-operations

Union of dict objects in Python


How do you calculate the union of two dict objects in Python, where a (key, value) pair is present in the result iff key is in either dict (unless there are duplicates)?

For example, the union of {'a' : 0, 'b' : 1} and {'c' : 2} is {'a' : 0, 'b' : 1, 'c' : 2}.

Preferably you can do this without modifying either input dict. Example of where this is useful: Get a dict of all variables currently in scope and their values


Solution

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