[Tutor] using re to build dictionary
Norman Khine
norman at khine.net
Tue Feb 24 12:48:51 CET 2009
Hello,
From my previous post on create dictionary from csv, i have broken the
problem further and wanted the lists feedback if it could be done better:
>>> s = 'Association of British Travel Agents (ABTA) No. 56542\nAir
Travel Organisation Licence (ATOL)\nAppointed Agents of IATA
(IATA)\nIncentive Travel & Meet. Association (ITMA)'
>>> licences = re.split("\n+", s)
>>> licence_list = [re.split("\((\w+)\)", licence) for licence in licences]
>>> association = []
>>> for x in licence_list:
... for y in x:
... if y.isupper():
... association.append(y)
...
>>> association
['ABTA', 'ATOL', 'IATA', 'ITMA']
In my string 's', I have 'No. 56542', how would I extract the '56542'
and map it against the 'ABTA' so that I can have a dictionary for example:
>>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''}
>>>
Here is what I have so far:
>>> my_dictionary = {}
>>> for x in licence_list:
... for y in x:
... if y.isupper():
... my_dictionary[y] = y
...
>>> my_dictionary
{'ABTA': 'ABTA', 'IATA': 'IATA', 'ITMA': 'ITMA', 'ATOL': 'ATOL'}
This is wrong as the values should be the 'decimal' i.e. 56542 that is
in the licence_list.
here is where I miss the point as in my licence_list, not all items have
a code, all but one are empty, for my usecase, I still need to create
the dictionary so that it is in the form:
>>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''}
Any advise much appreciated.
Norman
More information about the Tutor
mailing list