Skip to content Skip to sidebar Skip to footer

Python: Getting Sub-dicts In Dicts Dynamically?

Say I want to write a function which will return an arbitrary value from a dict, like: mydict['foo']['bar']['baz'], or return an empty string if it doesn't. However, I don't know i

Solution 1:

You should use the standard defaultdict: https://docs.python.org/2/library/collections.html#collections.defaultdict

For how to nest them, see: defaultdict of defaultdict, nested or Multiple levels of 'collection.defaultdict' in Python

I think this does what you want:

from collections import defaultdict
mydict = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))

Solution 2:

You might also want to check out addict.

>>> from addict import Dict
>>> addicted = Dict()
>>> addicted.a = 2
>>> addicted.b.c.d.e
{}
>>> addicted
{'a': 2, 'b': {'c': {'d': {'e': {}}}}}

It returns an empty Dict, not an empty string, but apart from that it looks like it does what you ask for in the question.


Post a Comment for "Python: Getting Sub-dicts In Dicts Dynamically?"