Dynamic Lists, or...?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jun 13 10:43:10 CEST 2005

On Sat, 11 Jun 2005 10:30:53 -0700, Lorn wrote:

> I'm trying to figure out a way to create dynamic lists or possibly
> antother solution for the following problem. I have multiple lines in a
> text file (every line is the same format) that are iterated over and
> which need to be compared to previous lines in the file in order to
> perform some simple math. Each line contains 3 fileds: a descriptor and
> two integers. Here is an example:
> rose, 1, 500
> lilac, 1, 300
> lilly, 1, 400
> rose, 0, 100
> The idea is that the 0/1 values are there to let the program know
> wether to add or subtract the second integer value for a specific
> descriptor (flower in this case). So the program comes upon rose, adds
> the 500 to an empty list, waits for the next appearance of the rose
> descriptor and then (in this case) subtracts 100 from 500 and prints
> the value. If the next rose was a 1 then it would have added 100.

Why not just use a leading minus sign for the number if it is to be
> I'm uncertain on how to approach doing this though. My idea was to
> somehow be able to create lists dynamically upon each new occurence of a
> descriptor that currently has no list and then perform the calculations
> from there. Unfortunately, the list of descriptors is potentially
> infinte, so I'm unable to previously create lists with the descriptor
> names. Could anyonw give any suggestions on how to best approach this
> problem, hopefully I've been clear enough? Any help would be very gratly
> appreciated.

Use a dictionary:

def update_dict(D, key, sign, value):
    """Update dictionary D item with key by adding 
    or subtracting value."""
    if not sign:
        value = -value
    x = D.get(key, 0)
    D[key] = x + value

def split_line(s):
    """Split a string s into a tuple (key, sign, value),
    ignoring whitespace."""
    L = s.split(",")
    return L[0].strip(), L[1].strip(), L[2].strip()
    # WARNING: insufficient error checking for real world use.

Then call them like this:

D = {}
for line in sourcetext:
    key, sign, value = split_line(line)
    update_dict(D, key, sign, value)

Oh, by the way... just in case this is homework, which I'm sure it isn't
<wink>, I've deliberately left a teeny tiny bug in the code. You'll find
the bug pretty much the first time you run it, and the fix is very simple.


More information about the Python-list mailing list