idea on how to get/set nested python dictionary values

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Aug 15 18:48:58 EDT 2006


wittempj at hotmail.com wrote:
> py> def SetNewDataParam2(Data, NewData):
> ...     if type(Data[Data.keys()[0]]) == type(dict()):
> ...         SetNewDataParam2(Data[Data.keys()[0]], NewData)
> ...     else:
> ...         Data[Data.keys()[0]] = NewData
> ...
> ...     return Data
> py> Data = {'a':{'b':{'c':1}}}
> py> NewData = 666
> py> ret = SetNewDataParam2(Data, NewData)
> py> print ret
> {'a': {'b': {'c': 666}}}

This looks better:

def setNested(nest, val):
    el = nest.iterkeys().next()
    if isinstance(nest[el], dict):
        setNested(nest[el], val)
    else:
        nest[el] = val
    return nest

But maybe something like this is closer to the OP needs:

def setNested(nest, path, val):
    nest2 = nest
    for key in path[:-1]:
        nest2 = nest2[key]
    nest2[path[-1]] = val
    return nest

ndict = {'a1':{'b1':{'c1':1}, "b2":{"c2":2}}}
print ndict
print setNested(ndict, ("a1", "b1", "c1"), 3)
print setNested(ndict, ("a1", "b2", "c2"), 4)

Output:
{'a1': {'b1': {'c1': 1}, 'b2': {'c2': 2}}}
{'a1': {'b1': {'c1': 3}, 'b2': {'c2': 2}}}
{'a1': {'b1': {'c1': 3}, 'b2': {'c2': 4}}}

(But I don't like too much that kind of in place modify.)

Bye,
bearophile




More information about the Python-list mailing list