'Can I write all "append" code in a row using "if"?
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})
Solution 1:[1]
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']
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Freddy Mcloughlan |
