Newbie query - reading text file (with column headings) into dictionary

Mike Meyer mwm at mired.org
Sun Dec 8 07:02:29 EST 2002


"Andy Elvey" <andy.elvey at paradise.net.nz> writes:
> Mike Meyer <mwm at mired.org> wrote in message

In the future, please edit your posts to remove any material that is
no longer relevant.

> > You either want a list of dictionaries, or for the dictionary to
> > return a list of items. Calling the result R, those would correspond
> > to R[0]["City"] == "Sydney" and R[1]["City"] == "Perth", or R["City"]
> > == ["Sydney", "Perth"]. In the latter case, what would R["Country"]
> > return? ["Australia"], or ["Australia", "Australia"].
>   Hi, Mike - thanks for this :-)  ( and apologies for not having clarified
> things more ).
>    I'm wanting your second option - for the dictionary to return a list of
> items.

That's almost trivial:

def load_csv(file):
    keys = map(string.strip, file.readline().split(","))
    result = {}
    for key in keys:
        result[key] = []
    for line in file:
        values = map(string.strip, line.split(","))
        for key, value in map(None, keys, values):
            result[key].append(value)
    return result

Personally, I don't think this belongs in a cookbook, because it
slices the data in an unusual direction. If you sliced it the other
way - making each line an object, instead of each column - then
accessing individual data elements is nearly identical: you just swap
the order of the subscripts. However, you're more likely to want to
deal with a line as an individual object than a column. For instance,
pulling all the records where Country is Australia is trivial if you
have lines instead of columns -
        filter(lambda a: a["Country"] = "Australia", lines)
but a major problem the way you've got the data sliced.

In fact, I've got a class designed for filtering lists of records
similar to what you would have slicing it the other way. It lets you
create custom filters by combining primitives or from other
filters. One of the few times I've wished that Python had macros.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list