473,320 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Can dictionaries be nested?

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 names I've made up to illustrate the point more clearly.

(the embedded device device can't produce XML and this is what I have
to deal with)

I want to populate a nested set of dictionaries where the outer most
dictionary has look-ups on the OuterNames:

InnerDict = OuterDict["OuterName2"]

Then InnerDict[InnerName3] would yield 21 in the above example.

First, can dictionaries contain dictionaries?

Second, how to create each successive inner dictionary when populating
it? Python doesn't have constructors and (having all of 4 weeks of
Python experience) it isn't clear to me whether in nested while loops
that variables ever go out of scope.

If I do:

OuterDict = {}
while populating dictionaries
InnerDict = {}
while inner stuff to populate
InnerDict["InnerName1"] = 5
.. and so on
:
OuterDict["OuterName1"] = InnerDict

then when I loop around the second time will the same InnerDict get
set back to an empty dictionary and therefore wipe out the dictionary I
put at OuterDict["OuterName1"] ?

I need a new inner dictionary each time thru the outer while loop. It
is not clear to me how to do this.

Jan 12 '06 #1
2 1983
te**********@futurepundit.com writes:
First, can dictionaries contain dictionaries?
Yes.
Second, how to create each successive inner dictionary when populating
it? Python doesn't have constructors and (having all of 4 weeks of
Python experience) it isn't clear to me whether in nested while loops
that variables ever go out of scope.
All variables stay in scope through the entire execution of the
function they're created in.
If I do:

OuterDict = {}
while populating dictionaries
InnerDict = {}
while inner stuff to populate
InnerDict["InnerName1"] = 5
.. and so on
:
OuterDict["OuterName1"] = InnerDict

then when I loop around the second time will the same InnerDict get
set back to an empty dictionary and therefore wipe out the dictionary I
put at OuterDict["OuterName1"] ?
It will get set to a newly created empty dictionary. The old
dictionary won't get wiped out, and will stay accessible through
OuterDict["OuterName1"].
I need a new inner dictionary each time thru the outer while loop. It
is not clear to me how to do this.


You've done it correctly. It's pretty easy to test this stuff by
experiment. You probably spent almost as much time posting to the
newsgroup as simply trying it would have taken:
people = {}
person = {}
person['age'] = 25
person['nationality'] = 'dutch'
people['john'] = person
people {'john': {'nationality': 'dutch', 'age': 25}} person = {} # make new dictionary
people # hasn't changed {'john': {'nationality': 'dutch', 'age': 25}} person['age'] = 3.6e25
person['nationality'] = 'cosmic'
people['FSM'] = person
people {'john': {'nationality': 'dutch', 'age': 25},
'FSM': {'nationality': 'cosmic', 'age': 3.6000000000000002e+25}}

Jan 12 '06 #2
<te**********@futurepundit.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
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....

I wrote pyparsing for just this kind of job. Using pyparsing, you can both
parse the data and build up structured results - even results with keyed
fields or dictionary-type access.

Here's the complete pyparsing program to parse your data:

---------------------------
data = """
OuterName1 InnerName1=5,InnerName2=7,InnerName3=34;
OuterName2 InnerNameX=43,InnerNameY=67,InnerName3=21;
"""
# or data = file(inputname).read()

from pyparsing import *

EQ = Literal("=").suppress()
SEMI = Literal(";").suppress()
ident = Word(alphas, alphanums+"_")
integer = Word(nums)

value = integer | quotedString

innerentry = Group(ident + EQ + value)

vallist = Dict(delimitedList(innerentry))
outerentry = Group(ident + vallist + SEMI)
datalist = Dict( ZeroOrMore(outerentry) )

vals = datalist.parseString(data)
print vals.keys()
print vals["OuterName1"]["InnerName2"]
print vals.OuterName2.InnerNameY

---------------------------

Prints:
['OuterName2', 'OuterName1']
7
67

Here's the same program, with a few more comments to explain what's going
on:
---------------------------
from pyparsing import *

# define expressions for some basic elements - use pyparsing's basic
# building blocks, Literal and Word
EQ = Literal("=").suppress()
SEMI = Literal(";").suppress()
ident = Word(alphas, alphanums+"_")
integer = Word(nums)

# expand this list to include other items you end up finding in values
value = integer | quotedString

# define the format of the list of InnerName entries
innerentry = Group(ident + EQ + value)

# delimitedList is a pyparsing helper for a list of expressions, separated
by
# some delimiter - default delimiter is a comma
vallist = delimitedList(innerentry)

# lastly, define the overall datalist
outerentry = Group(ident + vallist + SEMI)
datalist = ZeroOrMore( outerentry )

# extract the data into a structure using parseString
vals = datalist.parseString(data)

# prettyprint the results
import pprint
pprint.pprint(vals.asList())
print
# Refinement: have pyparsing build keyed results while
# it parses (accessible like a dict)
vallist = Dict(delimitedList(innerentry))
outerentry = Group(ident + vallist + SEMI)
datalist = Dict( ZeroOrMore(outerentry) )

# reparse using modified grammar
vals = datalist.parseString(data)

# view results using dict functions
print vals.keys()
print vals["OuterName1"]["InnerName2"]

# if keys are valid Python identifiers, can also access results
# like object fields
print vals.OuterName2.InnerNameY
---------------------------
Prints:

[['OuterName1',
['InnerName1', '5'],
['InnerName2', '7'],
['InnerName3', '34']],
['OuterName2',
['InnerNameX', '43'],
['InnerNameY', '67'],
['InnerName3', '21']]]

['OuterName2', 'OuterName1']
7
67

Download pyparsing at http://pyparsing.sourceforge.net. (I'm also making a
couple of pyparsing presentations at PyCon, next month.)

-- Paul
Jan 12 '06 #3

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

Similar topics

13
by: omission9 | last post by:
I have a dictionary that looks like this MY_DICT=FOO I am having a problem updating this with a simple MY_DICT.update(NEW_DICT) as update doesn't seem to care about getting into the inner...
9
by: T. Earle | last post by:
To list, I'm trying to figure out the best approach to the following problem: I have four variables: 1) headlines 2) times 3) states 4) zones
210
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again...
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...
1
by: hermesbaby | last post by:
I have a CSV-File which I convert to an array like this: , , , , , ]
0
by: d80013 | last post by:
Hello all, I am trying to create a Dictionary of dictionaries in VBA. All I do is declare two dictionaries, one temporary one, and add the temporary dictionary to the main one recursively. The...
1
by: qbob | last post by:
I have data that is essentially tree-like, and to store it/iterate over it I have been using nested dictionaries, eg: Dictionary<int, Dictionary<string, Dictionary<double>>> data = new ... to...
1
by: Matthew Schibler | last post by:
I'm a newbie to Python, with some experience using perl (where I used nested arrays and hashes extensively). I am building a script in python for a MUD I play, and I want to use the shelve module...
9
by: Brandon | last post by:
Hi all, I am not altogether experienced in Python, but I haven't been able to find a good example of the syntax that I'm looking for in any tutorial that I've seen. Hope somebody can point me...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.