Based on this source, I've made the following universal get / set function, to make it possible to work on OrderedDict trees for example.
def nested_expand_and_get(d, keys):
intermediate = d
for key in keys:
intermediate = intermediate.setdefault(key, d.__class__())
return intermediate
def nested_set(d, keys, value):
intermediate = nested_expand_and_get(d, keys[:-1])
intermediate[keys[-1]] = value
I've tested it on some examples I could come up with, but I'm not sure in two things:
- I've simplified quite a bit from the linked source, namely, I'm not using lambdas and I've removed the if line.
- I've also introduced the tree type auto-detection, which I believe should work well for uniform trees.
Is this function correct as long as the given tree is uniform (by which I mean that it only contains all dict or OrderedDict or etc. elements)? Would you recommend using something else for working on ordered trees (without external libs)?