[Tutor] Dictionaries

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 12 Nov 2001 20:59:16 -0800 (PST)


On Mon, 12 Nov 2001, Mike Yuen wrote:

> I have to use dictionaries for this particular portion.  I've got some
> data in the following format:
> 
> 1
>  a b c
>  d e f
>  g h i
> 
> 2
>  j k l
>  m n o
>  p q r
> 
> And so on.
> 
> What I want to do is have 1, 2,... as keys in my dictionary and have each
> of the next 3 rows as the data associated with the keys.  The problem i'm


Hello Mike,

I'm guessing that you'd like something to help parse a bunch of lines
following the format:

###
<Some Key>
    <element> <element> <element>
    <element> <element> <element>
    ...
<empty line>
###


That is, each record is separated by two newlines, and each record has a
fairly consistant format.  If so, then it's not too bad to parse your file
into a dictionary.  Here's some code that sorta does it, in a sloppy
fashion:


###
def parseTextFile(text_of_file):
    """Given a string containing all of the text, returns
    a dictionary that represents the parsing of that file."""
    fragments = string.split(text_of_file, "\n\n")
    dict = {}
    for f in fragments:
        key, value = parseFragment(f)
        dict[key] = value
    return dict


def parseFragment(fragment):
    lines = string.split(fragment, '\n')
    key = string.strip(lines[0])
    value = string.join(lines[1:], ' ')
    return key, value
###




We'd better test this out... *grin*  Let's take a look!

###
>>> sample = """1
... this is a test
... 
... 2
... of the emergency
... broadcast
... 
... 3
... system
... """
>>> parseTextFile(sample)
{'2': 'of the emergency broadcast', '3': 'system ', '1': 'this is a test'}
###


This isn't quite right, since what you're asking sounds more like:

###
    { 2: ['of', 'the', 'emergency', 'broadcast'],
      3: ['system'],
      1: ['this', 'is', 'a', 'test'] }
###

Still, parseTextFile() should help you write the function you're looking
for.


If you have more questions, please feel free to ask them on Tutor.  We'll
be happy to talk more about this.  Hope this helps!