location of member in list of dictionaries

Question:

if I have the following:

[{'place':1, 'acc':75}, {'place':2, 'acc':95}, {'place':3, 'acc':60}]

What would be the best way to get the value of the place which has the best accuracy ?
In this example the result would be: 2

Asked By: dani shamir

||

Answers:

It would be easier to use a list of lists. For example:

[[75, 1], [95, 2], [60, 3]]

For added convenience, perhaps organise them as [accuracy, place] instead of [place, accuracy]. Then you can iterate through the lists using a for loop and check each value, changing the current best place with each higher accuracy.
Edit: reading python tutorials and guides can also aid you in the future

Answered By: Forestral

The built-in max function allows you to specify a key. So, for your example, you could do this:

list_ = [{'place':1, 'acc':75}, {'place':2, 'acc':95}, {'place':3, 'acc':60}]

print(max(list_, key=lambda x: x['acc'])['place'])

Output:

2
Answered By: Stuart
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.