Search code examples
pythondictionarynesteddefaultdict

Checking a nested dictionary using a dot notation string "a.b.c.d.e", automatically create missing levels


Given the following dictionary:

d = {"a":{"b":{"c":"winning!"}}}

I have this string (from an external source, and I can't change this metaphor).

k = "a.b.c"

I need to determine if the dictionary has the key 'c', so I can add it if it doesn't.

This works swimmingly for retrieving a dot notation value:

reduce(dict.get, key.split("."), d)

but I can't figure out how to 'reduce' a has_key check or anything like that.

My ultimate problem is this: given "a.b.c.d.e", I need to create all the elements necessary in the dictionary, but not stomp them if they already exist.


Solution

  • ... or using recursion:

    def put(d, keys, item):
        if "." in keys:
            key, rest = keys.split(".", 1)
            if key not in d:
                d[key] = {}
            put(d[key], rest, item)
        else:
            d[keys] = item
    
    def get(d, keys):
        if "." in keys:
            key, rest = keys.split(".", 1)
            return get(d[key], rest)
        else:
            return d[keys]