2017-03-05 70 views
-2

我在Python的字典列表中擁有這組值。如何在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'} 
] 

如何根據字段「dep_price」將它們排序爲浮點值?

+4

的[我怎麼排序詞典列表可能的複製通過Python中的字典值?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-li st-of-dictionaries-by-values-of-the-dictionary-in-python) – ZdaR

+1

看起來你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出以及實際獲得的輸出(輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/questions/how-to-ask)。 – TigerhawkT3

+0

@ TigerhawkT3對不起,你錯了......這是我試過的那段代碼...... sorted(list,key = itemgetter(field_name),reverse = True)...其中field_name作爲「dep_price 「 – Razz

回答

3

可以使用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])) 

結果:

{'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'} 
+1

嘗試使用「100.205」的「dep_price」添加一些東西。 – TigerhawkT3

+1

@Stephen Rauch ......謝謝....我花了一些時間嘗試在解決方案中圍繞「lambda」和您對列表進行迭代的方式。現在排序。謝謝您的幫助 – Razz

相關問題