2

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'}]
timgeb
  • 76,762
  • 20
  • 123
  • 145
Fatih Akman
  • 39
  • 1
  • 5
  • Create a function to extract the security value (as number) from one list item and use it as `key` for `min` function over the list. – Michael Butscher Dec 08 '18 at 13:40
  • I'm certain this must be a duplicate, but I can't find a good dupe target right now. In any case, there are dozens of existing questions on Stack Overflow about manipulating a list of dicts, and about techniques like using the `key` argument of `min`, `max`, and `sorted`. – Daniel Pryden Dec 08 '18 at 13:50
  • For example, there's this highly upvoted question, which covers very similar ground: [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Daniel Pryden Dec 08 '18 at 13:54

4 Answers4

4

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'}
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
3

Similar to mehrdad-pedramfar's answer, but I prefer using itemgetter from the operator module for readability.

Setup:

from operator import itemgetter
data = [{'prisonniers': [], 'sécurité': '47'},{'prisonniers': [],'sécurité':'92'}, {'prisonniers': [], 'sécurité': '38'}]

Solution:

>>> min(data, key=itemgetter('sécurité'))
{'prisonniers': [], 'sécurité': '38'}
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You can use min to do that, setting as key securite for finding the minimum value:

inList = [{'prisonniers': [], 'securite': '47'},{'prisonniers': [],'securite':'92'}, {'prisonniers': [], 'securite': '38'}]

value = min(inList, key=lambda elem: elem['securite'])
print(value)

Output:

{'prisonniers': [], 'securite': '38'}

In the above example, I replaced é with e but it will work fine in your case too.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

You can use below code: Step: Find the least "sécurité" using min([ i['sécurité'] for i in input_list]) then use list comprehension again print the matching "sécurité" with minimum value:

aa = [print(i) for j in input_list if j['sécurité'] == min([ i['sécurité'] for i in input_list])]
Akash Swain
  • 520
  • 3
  • 13