idea on how to get/set nested python dictionary values

wittempj@hotmail.com martin.witte at gmail.com
Tue Aug 15 17:53:37 EDT 2006


jojoba wrote:
> hello!
>
> i am trying to come up with a simple way to access my values in my
> nested python dictionaries
>
> here is what i have so far, but i wanted to run it by the geniuses out
> there who might see any probems with this...
> here is an example:
>
> +++++++++++++++++++++++++++++++++++++++
> def SetNewDataParam(Data, paramPath, NewData):
>     ParamList  = paramPath.split('/')
>     numParams  = len(ParamList)
>     for i in range(0, numParams):
>         if i != (numParams-1):
>             Data = Data[ParamList[i]]
>         else:
>             Data[ParamList[i]] = NewData
>

when I add here
               ret Data
>
> Data          = {'a':{'b':{'c':1}}}
> paramPath = 'a/b/c'
> NewData    = 666
> SetNewDataParam(Data, paramPath, NewData)

and change this to
ret = SetNewDataParam(Data, paramPath, NewData)
print ret
the shell returns me
{'c': 666}

> +++++++++++++++++++++++++++++++++++++++
>
>
> so it works!
> when i do:
> print Data, i get
> {'a':{'b':{'c':666}}}
>
>
> but i am hesistant to be throwing around dictionary references
> how is this working????
> shouldn't my line above:
> Data = Data[ParamList[i]]
> screw up my original Data dictionary
>
> Thanks to anyone with comments on this
> By the way, i love the idea of using tuples as keys, but my code is so
> far along that i dont wanna switch to that elegant way (maybe on a
> future project!)
> take care,
> jojoba

| would use a recursive approach for this - given that you have a sort
of recursive datastructure:

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




More information about the Python-list mailing list