Newbie query - reading text file (with column headings) into dictionary
Andy Elvey
andy.elvey at paradise.net.nz
Sat Dec 7 22:53:56 EST 2002
Mike Meyer <mwm at mired.org> wrote in message
news:x7isy5qt4u.fsf at guru.mired.org...
> "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
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.
So, the keys and their values would be as follows -
Key = "Country" Value = ['Australia', 'Australia']
Key= "City" Value = ['Sydney' , 'Perth']
Key = Var1 Value = [ 123, 415]
Key = Var2 Value = [456, 201 ]
Key = Var3 Value = [789, 142 ]
- Andy
More information about the Python-list
mailing list