[Tutor] sql-like join on two lists or dictionaries
Alan Gauld
alan.gauld at btinternet.com
Sat Feb 14 14:03:48 CET 2015
On 14/02/15 09:55, Peter Otten wrote:
> with open(headerfile) as f:
> lookup_header = {
> headerdata[:6]: headerdata.rstrip("\n") for headerdata in f}
>
> Then you can iterate over the lines in linefile, extract the key from that
> and look it up in the dict:
>
> with open(linefile) as lines, open("hl.dat", "w") as joined:
> for line in lines:
> try:
> header = lookup_header[line[:6]]
> except KeyError:
> header = ""
> print(line.rstrip("\n"), header, sep="", file=joined)
>
The try/except could be written more concisely as
header = lookup_header.get(line[:6], "")
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list