[Tutor] sql-like join on two lists or dictionaries
Joel Goldstick
joel.goldstick at gmail.com
Sat Feb 14 15:40:09 CET 2015
On Sat, Feb 14, 2015 at 8:03 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:
> 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
>
> You can dispense with the slicing if you use the str.split() method. It
> will put each item in a list.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
--
Joel Goldstick
http://joelgoldstick.com
More information about the Tutor
mailing list