makenested#

makenested(obj, keylist=None, value=None, overwrite=True, generator=None, copy=False)[source]#

Make a nested object (such as a dictionary).

Parameters:
  • obj (any) – the object to make the nested list in

  • keylist (list) – a list of keys (strings) of the path to make

  • value (any) – the value to set at the final key

  • overwrite (bool) – if True, overwrite a value even if it exists

  • generator (class/func) – the function used to create new levels of nesting (default: same as original object)

  • copy (bool) – if True, copy the object before modifying it

Functions to get and set data from nested dictionaries (including objects).

sc.getnested() will get the value for the given list of keys:

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

sc.setnested will set the value for the given list of keys:

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

sc.makenested will recursively update a dictionary with the given list of keys:

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

sc.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}}}

Example 3:

foo = sc.makenested(sc.prettyobj(), ['level1', 'level2', 'level3'], 'done')
assert foo.level1.level2.level3 == 'done'
New in version 2014nov29.
New in version 3.2.0: operate on arbitrary objects; “overwrite” defaults to True; returns object