Posts

Showing posts with the label dict unpacking

Two ways to combine two dictionaries with unique keys


Two ways to combe and merge two dictionaries in python: Union operator and dict unpacking

How do we combine 2 dictionaries when they have no intersecting keys and we don't want to modifiy any one of the two original dicts? First, we can combine them with the dict union operator, i.e. |. The dict union operator is available since Python v3.9. If a key would appear in both dicts, the union operator takes the value from the right hand-side dict, i.e. from the last seen. Second, we can use dict unpacking to merge our 2 dicts. For both methods the order of the keys in the combined dict is given by the order of the dicts in the union or unpacking operation.


Github gist with code

dependencies: python3.9