G
G
George2018-10-06 17:47:21
Python
George, 2018-10-06 17:47:21

How to sort list of dictionaries by value?

let's say there are 3 dictionaries, with the values ​​name: and price:
the elements with the lowest price value will go first, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
igorzakhar, 2018-10-06
@hatepls

>>> l = [{'name': 'C', 'price': 5}, {'name': 'A', 'price': 2}, {'name': 'B', 'price': 1}]
>>> newlist = sorted(l, key=lambda k: k['price'])
>>> newlist
[{'name': 'B', 'price': 1}, {'name': 'A', 'price': 2}, {'name': 'C', 'price': 5}]

Special for longclaps :
>>> from operator import itemgetter
>>> newlist = sorted(l, key=itemgetter('price'))
>>> newlist
[{'name': 'B', 'price': 1}, {'name': 'A', 'price': 2}, {'name': 'C', 'price': 5}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question