0

how can I in python append by condition, can i write like this?

'Segment 2': result['trips'][0]['segments'][2]['bookingClass']) if(len(result['trips'][0]['segments'] == 2,

at the moment i try to write all in one row, is this possible?

response.append({'Fare Type': result['fareType'], 'Segment 2': result['trips'][0]['segments'][2]['bookingClass']) if(len(result['trips'][0]['segments'] == 2})
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29

1 Answers1

0

You can (using a ternary operator):

response.append({'Fare Type': result['fareType'],'Segment 2': result['trips'][0]['segments'][2]['bookingClass']}) if(len(result['trips'][0]['segments'] == 2)) else None

But probably shouldn't, as this way has a useless else statement at the end, and is difficult to read. The code will be much simpler with an if statement:

if len(result['trips'][0]['segments']) == 2:
    response.append({
        'Fare Type': result['fareType'],
        'Segment 2': result['trips'][0]['segments'][2]['bookingClass']
    })
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29