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

Mike Meyer mwm at mired.org
Sat Dec 7 18:57:53 EST 2002


"Andy Elvey" <andy.elvey at paradise.net.nz> writes:
> Hi all.
>   I have a text file (comma separated) which looks like this -
>  Country, City,  Var1, Var2, Var3
>  Australia, Sydney, 123,456,789
>  Australia, Perth, 415, 201, 142
>  .... and so on.

There's actually an RFC that describes this file format. It's called
"Comma Separated Values". The other common alternative is Tab
Seperated Values.

>   I want to read the file into a dictionary so that the column headings
> (Country, city ,... ) are the keys, and the rest of the file is slotted into
> the appropriate key ( so that "Australia" has "Country" as the key, "Sydney"
> and "Perth" have "City" as the key, and so on.  This must be quite
> straightforward to do, but searching the 'net (including the Python Cookbook
> site) turns up nothing along these lines .... So - any help is very much
> appreciated.

Your problem isn't sufficiently well defined.  A dictionary lookup by
key returns a single value. But you have both Sydney and Perth "have"
the key "City". Given that the resulting dictionary is D, what would
D["City"] return?

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"].

        <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