472,371 Members | 1,534 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,371 software developers and data experts.

idea on how to get/set nested python dictionary values

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
Data = {'a':{'b':{'c':1}}}
paramPath = 'a/b/c'
NewData = 666
SetNewDataParam(Data, paramPath, NewData)
+++++++++++++++++++++++++++++++++++++++
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

Aug 15 '06 #1
9 3121
....

Aug 15 '06 #2

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:

pydef 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
pyData = {'a':{'b':{'c':1}}}
pyNewData = 666
pyret = SetNewDataParam2(Data, NewData)
pyprint ret
{'a': {'b': {'c': 666}}}

Aug 15 '06 #3
hey thank you so much!
that should work fantastically
i like your method much better
more elegant
thanks!

jojoba
=)

Aug 15 '06 #4
wi******@hotmail.com wrote:
pydef 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
pyData = {'a':{'b':{'c':1}}}
pyNewData = 666
pyret = SetNewDataParam2(Data, NewData)
pyprint 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

Aug 15 '06 #5
Like for the list.sort() method, to remind you that this function
operate by side effect, maybe it's better if it doesn't return the
modified nested dict:

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

Bye,
bearophile

Aug 15 '06 #6
wi******@hotmail.com wrote:
| would use a recursive approach for this - given that you have a sort
of recursive datastructure:

pydef SetNewDataParam2(Data, NewData):
... if type(Data[Data.keys()[0]]) == type(dict()):

Note:

|>type(dict()) is dict
True

"dict" *is* a type...

Aug 15 '06 #7
Once again,
Thanks to all!!!!
I did not expect to receive such a response.
Very very helpful indeed,

jojoba

o(-_-)o

Aug 16 '06 #8

wi******@hotmail.com wrote:
| would use a recursive approach for this - given that you have a sort
of recursive datastructure:

pydef SetNewDataParam2(Data, NewData):
... if type(Data[Data.keys()[0]]) == type(dict()):
... SetNewDataParam2(Data[Data.keys()[0]], NewData)
... else:
... Data[Data.keys()[0]] = NewData
...
Data[Data.keys()[0]] is used 3 times in the above code. Is there some
way to factor out that usage? I'm just starting python but I'm always
on the lookout for DRY :)

Aug 16 '06 #9

metaperl wrote:
wi******@hotmail.com wrote:
| would use a recursive approach for this - given that you have a sort
of recursive datastructure:

pydef SetNewDataParam2(Data, NewData):
... if type(Data[Data.keys()[0]]) == type(dict()):
... SetNewDataParam2(Data[Data.keys()[0]], NewData)
... else:
... Data[Data.keys()[0]] = NewData
...

Data[Data.keys()[0]] is used 3 times in the above code. Is there some
way to factor out that usage? I'm just starting python but I'm always
on the lookout for DRY :)
Bearophilehugs gave a much better answer than I did, it also takes away
the need to evaluate the keys() more than one time

Aug 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: kbass | last post by:
I am new to Python and I am attempting to retrieve data from a database and I would like to place this data into a nested dictionary. After placing the data into a dictionary, I would like to loop...
9
by: OKB (not okblacke) | last post by:
For a variety of reasons, I'm interested in putting together some code that will allow me to created structures out of nested classes, something like: class class1: def methA(self): print...
2
by: quadric | last post by:
Hi, I would like to pass a dictionary from my Python code to my Python extension, extract various values from the dictionary (from within the extension) , modify the values for the relevant...
2
by: techiepundit | last post by:
I'm parsing some data of the form: OuterName1 InnerName1=5,InnerName2=7,InnerName3=34; OuterName2 InnerNameX=43,InnerNameY=67,InnerName3=21; OuterName3 .... and so on.... These are fake...
3
by: Jake Emerson | last post by:
I'm attempting to build a process that helps me to evaluate the performance of weather stations. The script below operates on an MS Access database, brings back some data, and then loops through to...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
12
by: Rich Shepard | last post by:
I want to code what would be nested "for" loops in C, but I don't know the most elegant way of doing the same thing in python. So I need to learn how from you folks. Here's what I need to do: build...
1
by: Sam Loxton | last post by:
Hi, I am fairly new to the python language and am trying to sort a nested Dictionary of a Dictionary which I wish to sort by value. The dictionary does not have to be restructured as I only need...
16
by: IamIan | last post by:
Hello, I'm writing a simple FTP log parser that sums file sizes as it runs. I have a yearTotals dictionary with year keys and the monthTotals dictionary as its values. The monthTotals dictionary...
2
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
1
by: ezappsrUS | last post by:
Hi, I wonder if someone knows where I am going wrong below. I have a continuous form and two labels where only one would be visible depending on the checkbox being checked or not. Below is the...
0
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.