Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

  1. I've simplified quite a bit from the linked source, namely, I'm not using lambdas and I've removed the if line.
  2. 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)?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.