如何在Python中对字典列表(使用浮点值字段)进行排序?

Raz*_*azz -2 python sorting floating-point

我在 Python 的字典列表中有这组值。

[
{'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'}, 
{'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'}, 
{'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'}
]
Run Code Online (Sandbox Code Playgroud)

如何根据字段“dep_price”作为浮点值对它们进行排序?

Ste*_*uch 5

您可以使用sorted()关键功能:

代码:

a_list = [
    {'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'}
]

a_new_list = sorted(a_list, key=lambda price: float(price['dep_price']))
print('\n'.join(['%s' % x for x in a_new_list]))
Run Code Online (Sandbox Code Playgroud)

结果:

{'trip_type': 'dep', 'dep_price': '36.350', 'dep_date': '10-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '8-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '9-Mar-2017'}
Run Code Online (Sandbox Code Playgroud)