1

Assuming, below is the input list which has exp_date and qty field as blank/spaces/null.

input_lst = [
{
 "id": "123456",
 "product": "XYZ",
 "exp_date": "",
 "amount": "30.5",
 "qty": "1"
},
{
 "id": "789012",
 "product": "ABC",
 "exp_date": "04/15/2020",
 "amount": "22.57",
 "qty": "3"
},
{
 "id": "56789",
 "product": "AAA",
 "exp_date": "03/29/2020",
 "amount": "2",
 "qty": " "
}
]

Can we write if/then/else like below - what is the correct/appropriate syntax ?

output_lst = []

for dct in input_lst:
    tmp_dct = dct.copy()
    try:
    #replace/default any blank/null/space values and convert to datetime
        tmp_dct['exp_date'] = datetime.strptime(if dct['exp_date'] == "" then '01/01/1900' else dct['exp_date'], '%m/%d/%Y')
    except:
        pass
    #replace/default any blank/null/space values and convert to int
    try:
        tmp_dct['qty'] = int(if dct['qty'] == '' then '1' else dct['qty'])
    except:
    output_lst.append(tmp_dct)
print(output_lst)

Thanks!

ManiK
  • 377
  • 1
  • 21

1 Answers1

1

You must to change the order of your ternary operator:

output_lst = []

for dct in input_lst:
    tmp_dct = dct.copy()
    try:
        #replace/default any blank/null/space values and convert to datetime
        tmp_dct['exp_date'] = datetime.strptime('01/01/1900' if dct['exp_date'] == "" else dct['exp_date'], '%m/%d/%Y')
    except:
        pass

    try:
        #replace/default any blank/null/space values and convert to int
        tmp_dct['qty'] = 1 if dct['qty'].strip() == '' else int(dct['qty'])
    except:
        pass

    output_lst.append(tmp_dct)
print(output_lst)

You must also be careful with the field qty, that in your example can hold a whitespace. In cases like this, it's better to apply a strip() to remove any whitespaces in the beginning and/or end.

Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51