Want to merge two dictionaries into a new third dictionary without modifying either of the originals? Easy:
>>> dict3 = dict(dict1, **dict2)
Keys in dict2 would override matching keys in dict1. And, as usual, mutable values would be preserved by reference...
Personally I've always wished that dicts would define __add__
to do
this... something like:
class MyDict(dict):
def __add__(self, other):
return MyDict(self, **other)
if __name__ == '__main__':
d1 = MyDict(foo=1)
d2 = MyDict(bar=2, baz=3)
d3 = MyDict(qux=4)
d4 = d1 + d2 + d3
import pprint
pprint.pprint(d4)
# What if keys collide? Last one wins.
d5 = d4 + {'foo': 99} + {'foo': 999}
pprint.pprint(d5)