[英]sorting nested dicts with lists in python
I have a python dict that is like我有一个 python 字典,就像
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 '.我想根据 object 的值对“航班”列表进行排序,该值在“ AdultBaseFare ”下的“ Flight_Fare ”内具有最便宜的价格。
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. “航班”中的每个 object 用于一个航班,每个航班都有不同的舱位(例如,一个用于经济舱,一个用于商务舱),每个 class 都有不同的价格。 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)
我想对整个“航班”列表进行排序,以便“航班”列表中的第一个 object 是价格最低的航班(该航班中的另一个 class 是否比下一个航班更贵并不重要)
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.我认为最好的方法是首先对每个航班的“ Flight_Fare ”列表进行排序(以便每个航班的类别根据价格进行排序),然后根据“航班”中第一个 object 的价格对“航班”列表进行排序Flight_Fare ' 在那个航班上。
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只需制作 function 即可获得每个航班最便宜的成人基本票价,并将其用作
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.