Skip to content
scipython.com

P4.3.4IBAN code lengths

The file iban_lengths.txt contains two columns of data: a two-letter country code and the length of that country's International Bank Account Number (IBAN):

AL 28
AD 24
...
GB 22

The code snippet below parses the file into a dictionary of lengths, keyed by the country code:

iban_lengths = {}
with open('iban_lengths.txt') as fi:
    for line in fi.readlines():
        fields = line.split()
        iban_lengths[fields[0]] = int(fields[1])

Use a lambda function and list comprehension to achieve the same goal in (a) two lines, (b) one line.

Show solution

(a) One way is to use a lambda function to process the line fields (split on whitespace) into a tuple of a string and an integer:

process_fields = lambda f: (f[0], int(f[1]))
iban_lengths = dict([process_fields(line.split()) for line in
                            open('iban_lengths.txt').readlines()])

(b) The lambda function does not actually have to be assigned to a variable name:

iban_lengths = dict([(lambda f: (f[0], int(f[1])))(line.split())
                        for line in open('iban_lengths.txt').readlines()])

Disclaimer: the above code, whilst shorter, is much harder to understand than the original, multi-line alternative and does not lead to significant performance improvements.