The mechanism in YAML that could help you out is using anchors and aliases. With those you have to watch out though, because when you alias a YAML mapping (loaded as a Python dict
), that you will get the same instance of that dict
attached to item1
and item2
.
If that is not what you want there is a specific interpretation of an alias in the form of a merge key. To use that specify a key <<
:
item1: &repl
it_one:
some: {...}
it_two:
somemore: {...}
item2:
<<: *repl
this will give you, at least directly under item2
a new dict with the same keys/values as for item1
(i.e. keys it_one
, it_two
). However again the values for those keys (some: {}
) will be the same object, due to the way this is loaded and handled internally.
If that kind of object reuse is problematic, you better stick with a non-merge use of the alias:
item1: &repl
it_one:
some: {...}
it_two:
somemore: {...}
item2: *repl
and walk over the tree recursively duplicating the key-values in new dicts (and lists).
Please note that if you use the round_trip_loader
in ruamel.yaml
, you will even share the everything, even when using merge keys. Without that round-tripping would not be possible, so use the safe_loader
instead.