python - Dynamic dict value access with dot separated string -


i'm using python 3.5.1

so trying pass in dict dot separated string representing path key , default value. want check keys existence , if it's not there , provide default value. problem key want access nested in other dicts , not know until run time. want this:

def replace_key(the_dict, dict_key, default_value):     if dict_key not in the_dict:        the_dict[dict_key] = default_value     return the_dict  some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}} key_to_replace = 'top_property.first_nested.second_nested' default_value = 'replaced' #this return {'top_property': {'first_nested': {'second_nested': 'replaced'}}} replace_key(some_dict, key_to_replace, default_value)  

what i'm looking way without having split on '.' in string , iterating on possible keys messy. rather not have use third party library. feel there clean built in pythonic way can't find it. i've dug through docs no avail. if has suggestion how appreciated. thanks!

you use recursivity:

def replace_key(the_dict, dict_keys, default_value):     if dict_keys[0] in the_dict:         if len(dict_keys)==1:             the_dict[dict_keys[0]]=default_value         else:             replace_key(the_dict[dict_keys[0]], dict_keys[1:],default_value)     else:         raise exception("wrong key")   some_dict = {'top_property': {'first_nested': {'second_nested': 'the value'}}} key_to_replace = 'top_property.first_nested.second_nested' default_value = 'replaced' #this return {'top_property': {'first_nested': {'second_nested': 'replaced'}}} replace_key(some_dict, key_to_replace.split("."), default_value) 

but still uses split(). maybe consider less messy?


Comments