[Tutor] sql-like join on two lists or dictionaries

Peter Otten __peter__ at web.de
Sun Feb 15 20:36:03 CET 2015


Alan Gauld 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], "")

Yep, I originally had something like

for line in lines:
    try:
        header = lookup_header[line[:6]]
    except KeyError:
        contine
    print(...)

in mind.

By the way, the 

print(..., sep="", ...) # no idea why I did this

is wrong and should be omitted. Also, you (OP) probably don't want the key 
column to appear twice in the output, so the second occurence can be sliced 
off:

print(line.rstrip("\n"), header[6:], file=joined)




More information about the Tutor mailing list