Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the minimum of a list of dictionaries with respect to a specific key

I have this :

[{'prisonniers': [], 'sécurité': '47'},{'prisonniers': [],'sécurité':'92'}, {'prisonniers': [], 'sécurité': '38'}]

And I need to put inside another list the dict which has the lowest 'sécurity', in this case, I need this:

myList = [{'prisonniers': [], 'sécurité': '38'}]
like image 569
Fatih Akman Avatar asked Oct 31 '25 21:10

Fatih Akman


1 Answers

min function accepts an argument named key, it will find the minimum of an iterable based on key that can be callable. so, try this:

l = [{'prisonniers': [], 'sécurité': '47'},{'prisonniers': [],'sécurité':'92'}, {'prisonniers': [], 'sécurité': '38'}]

min(l, key=lambda x:x['sécurité'])

the output will be

{'prisonniers': [], 'sécurité': '38'}
like image 179
Mehrdad Pedramfar Avatar answered Nov 02 '25 11:11

Mehrdad Pedramfar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!