-2

I have this set of values in a list of dictionaries in 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'}
]

How can I sort them based on field "dep_price" as a float value?

Razz
  • 29
  • 5
  • 4
    Possible duplicate of [How do I sort a list of dictionaries by values of the dictionary in Python?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – ZdaR Mar 05 '17 at 07:25
  • 1
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/questions/how-to-ask). – TigerhawkT3 Mar 05 '17 at 07:33
  • @TigerhawkT3 sorry you are mistaken... here is the piece of code that I tried ......sorted(list, key=itemgetter(field_name),reverse=True)... where field_name is passed as "dep_price" – Razz Mar 05 '17 at 07:37
  • How am I mistaken? I see no code, no attempt whatsoever to resolve this yourself, not even any preliminary thoughts from you... just a task and a request for a solution. – TigerhawkT3 Mar 05 '17 at 07:39

1 Answers1

5

You can use sorted() with a key function:

Code:

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]))

Results:

{'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'}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • 1
    Try adding something with a `'dep_price'` of, say, `'100.205'`. – TigerhawkT3 Mar 05 '17 at 07:31
  • 1
    @Stephen Rauch ... thanks.... it took me some time to try to wrap my head around the "lambda" in your solution and the way you have done the iteration over the list. Sorted now. Thanks for the help – Razz Mar 05 '17 at 08:06