recursive n-th child dict.get() - efficiency?
python
Solution
One suggestion I have is to give `split()` a second argument. You can do something simpler like:
parent, rest = string.split(".", 1)
Other than that, I see no immediate issues with the code.
You can also do this without recursion:
def recursive_dict_get(item, string, default=False):
for s in string.split('.'):
if (isinstance(item, dict) and s in item):
item = item[s]
else:
return default
return item
Problem
I need to get some values out of some big nested dictionaries. Out of laziness I decided to write a function that recursively calls itself until the last child is found, or the leaf is empty. Since there are dictionaries popped out and with every new call there's a new dictionary built, I wonder how efficient this is. Any suggestions? ``` def recursive_dict_get(item, string, default=False): if not isinstance(item, dict): return default print "called with ", item, "and string", string if "." in string: attrs = string.split(".") parent = attrs.pop(0) rest = ".".join(attrs) result = item.get(parent, None) if result is None: return default else: return recursive_dict_get(item.get(parent, default), rest, default) else: return item.get(string, default) ``` --- ``` foo = { "1": { "2": { "3": { "4":{ "5": { "6": { "7": "juice" } } } } } } } print recursive_dict_get(foo, "1.2.3.4.5.6.7", False) print "*" * 3 print recursive_dict_get(foo, "1.2.3.4.5.6", False) print "*" * 3 print recursive_dict_get(foo, "1.3", False) ```