2

Possible Duplicate:
Checking a Dictionary using a dot notation string

There is a multi-levels dict like this:

some_infomations = {
    "root":{
        "sub":{
            "more_deep":{
                "not_enough": "Some value",
                "another": "bla..bla"
            }
        },
        "more":{
            "more_deep":{
                "not_enough": "Some value",
                "another": "bla..bla"
            }
        }
    }
}

I have a crumbs string such as root.sub.more_deep.another, is there a simple and good way to do the work just like eval("some_infomations[root.sub.more_deep.another] = some_value")?

Community
  • 1
  • 1
kimjxie
  • 641
  • 7
  • 11

1 Answers1

1

Posted here mostly for fun, but also because reduce has a lot more use than most people give it credit for...:

from operator import getitem
def dot_get(your_dict,s):
    return reduce(getitem, s.split('.'), your_dict)  

d = {'foo': {'bar': {'baz': 1}}}
print dot_pull(d,'foo.bar.baz')

EDIT -- Apparently this is how OP did it in the previous question that I didn't read quite carefully enough, although OP used dict.get which will suppress a KeyError.

To set an item, you'd need to split off the last element, and get the one above it:

def dot_set(your_dict,s,v):
    head,tail = s.rsplit('.',1)
    dot_get(yourdict,head)[tail] = v
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I don't know how to format my answer properly, I've pasted it here: https://gist.github.com/veverjak/72fa753f5e4234647835 – user1830432 Feb 16 '15 at 17:31