Dict Tricks
Merging made easy
Created: 2022-01-04
x = {"one": 1}
y = {"two": 2}
z = x | y; z
{'one': 1, 'two': 2}
For me, this replaces merging a dict like so:
z = {**x, **y}; z
{'one': 1, 'two': 2}
For more complex cases, check out the builtin ChainMap
which also handles simple merging
from collections import ChainMap
z = dict(ChainMap(x, y)); z
{'two': 2, 'one': 1}
Example where we want to inherit from a parent dictionary but create separate contexts with
d = ChainMap({"version": 2, "resource": None})
cam_one = d.new_child({"resource": "Cam1", "objects": []})
cam_two = d.new_child({"resource": "Cam2", "objects": []})
cam_one['objects'] = [{"type": "car", "value": 0.86}]
cam_two['objects'] = [{"type": "truck", "value": 0.5}]
print(dict(cam_one))
print(dict(cam_two))
{'version': 2, 'resource': 'Cam1', 'objects': [{'type': 'car', 'value': 0.86}]} {'version': 2, 'resource': 'Cam2', 'objects': [{'type': 'truck', 'value': 0.5}]}
There's lot more that can be done with the ChainMap
. Check out the docs!