line split - how can I retain columns with missing values

Viewed 240

I am processing a form output where all fields are not mandatory to be filled. I am reading the values into a dictionary, splitting it and then doing some processing. However, I am finding that when there are values missing then entire column is dropped. So in the example below, since this record has missing data for EndMonth, EndDay, EndYear - these three columns are dropped from the output even though other records have data for it.

FirstName       Oliver
LastName        Twist
PhoneNumber     8111456789
EmailAddress    xjk@py.com
StartMonth       2
StartDay 3
StartYear        2020
EndMonth
EndDay
EndYear

My code goes something like this....how can I replace the missing value with something like 'blank' or 'NA' to ensure no records get dropped. I am sure this is an easy one but I am a python newbie and so struggling with it

file=open("ztest.txt", "r")
dict_vals={}
for line in file:
    if line.rstrip():
        split_line=line.split()
.....

Thanks

1 Answers

If there is no value associated with the key, line.split() will only have length 1:

'FirstName       Oliver'.split()  # ['FirstName', 'Oliver']
'EndDay    '.split()  # ['EndDay']

So the logic could go like:

split_line=line.split()
if len(split_line) == 1:
    split_line.append('NA')

Other possible improvement: define the character to split on explicitely, it may avoid bugs later on. In your case, ' ' or '\t' should do.

Related