makenested#

makenested(nesteddict, keylist=None, value=None, overwrite=False, generator=None)[source]#

Little functions to get and set data from nested dictionaries.

The first two were adapted from: http://stackoverflow.com/questions/14692690/access-python-nested-dictionary-items-via-a-list-of-keys

“getnested” will get the value for the given list of keys:

>>> sc.getnested(foo, ['a','b'])

“setnested” will set the value for the given list of keys:

>>> sc.setnested(foo, ['a','b'], 3)

“makenested” will recursively update a dictionary with the given list of keys:

>>> sc.makenested(foo, ['a','b'])

“iternested” will return a list of all the twigs in the current dictionary:

>>> twigs = sc.iternested(foo)

Example 1:

foo = {}
sc.makenested(foo, ['a','b'])
foo['a']['b'] = 3
print(sc.getnested(foo, ['a','b']))    # 3
sc.setnested(foo, ['a','b'], 7)
print(sc.getnested(foo, ['a','b']))    # 7
sc.makenested(foo, ['bar','cat'])
sc.setnested(foo, ['bar','cat'], 'in the hat')
print(foo['bar'])  # {'cat': 'in the hat'}

Example 2:

foo = {}
sc.makenested(foo, ['a','x'])
sc.makenested(foo, ['a','y'])
sc.makenested(foo, ['a','z'])
sc.makenested(foo, ['b','a','x'])
sc.makenested(foo, ['b','a','y'])
count = 0
for twig in sc.iternested(foo):
    count += 1
    sc.setnested(foo, twig, count)   # {'a': {'y': 1, 'x': 2, 'z': 3}, 'b': {'a': {'y': 4, 'x': 5}}}

Version: 2014nov29