I have a python dict that is like
flights = [
{
"Flight_Fare": [
{"M": {"AvailableSets": "9+", "AdultBaseFare": "20"}},
{"N": {"AvailableSets": "9+", "AdultBaseFare": "30"}},
]
},
{
"Flight_Fare": [
{"M": {"AvailableSets": "9+", "AdultBaseFare": "40"}},
{"N": {"AvailableSets": "9+", "AdultBaseFare": "10"}},
]
},
]
I would like to sort the ' Flights ' list based on the value of the object that has the cheapest price inside ' Flight_Fare ' under its ' AdultBaseFare '.
So you can look at it like this,
each object inside ' Flights ' is for a flight and each flight has different classes (ex. one for Economy one for Bussiness) and each class has a different price. I want to sort the whole " Flight " list so that the first object inside the ' Flight ' list is the flight that has the cheapest price (doesn't matter if the other class in that flight is more expensive then the next flight)
I think the best way would be to first sort the ' Flight_Fare ' list of each Flight (so that each flight has its classes sorted based on the price) and then sort the ' Flight ' list based on the price of the first object in ' Flight_Fare ' in that flight.
can someone please help me with this?
just make a function to get the cheapest adultbasefare for each flight and use it as the key for the sorted
function
def get_cheapest(flight):
fares = []
for f in flight['Flight_Fare']:
for key in f.keys():
fares.append(f[key]['AdultBaseFare'])
return float(min(fares))
flights = [
{
"Flight_Fare": [
{"M": {"AvailableSets": "9+", "AdultBaseFare": "20"}},
{"N": {"AvailableSets": "9+", "AdultBaseFare": "30"}},
]
},
{
"Flight_Fare": [
{"M": {"AvailableSets": "9+", "AdultBaseFare": "40"}},
{"N": {"AvailableSets": "9+", "AdultBaseFare": "10"}},
]
},
]
out = sorted(flights, key=lambda x: get_cheapest(x))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.