IBAN code lengths

Question P4.3.4

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.


To access solutions, please obtain an access code from Cambridge University Press at the Lecturer Resources page for my book (registration required) and then sign up to scipython.com providing this code.