2

could someone help me select the minimum value between two keys? For example, if I have the list of dictionaries:

results = [
  {
    "model": "short",
    "score": 34,
    "alt_score": 1
  }, 
  {
    "model": "med",
    "score": 22,
    "alt_score": 11
  }, 
  {
    "model": "tall",
    "score": 42,
    "alt_score": 90
  }, 
  {
    "model": "xtall",
    "score": 83,
    "alt_score": 15
  }, 
]

I want to select the dictionary that has the smallest score OR alt_score. I know how to find the dictionary w/ the smallest score or alt_score individually:

min(results, key=lambda x:x['alt_score'])

but I'm not sure how to look at two keys at once. I would need something like:

min(results, key=lambda x:x['score', 'alt_score])

or

min(results, key=lambda x:x['score'] or x:x['alt_score'])

the result should return:

{
  "model": "short",
  "score": 34,
  "alt_score": 1
}

Thanks in advance!

0

4 Answers 4

6
min(results, key=lambda x:min(x['score'], x['alt_score']))

Lambdas can have pretty much any expression in them, including an internal call to min() to get whichever is smaller for the item, score or alt_score.

Sign up to request clarification or add additional context in comments.

Comments

3

You could use this:

min(results, key=lambda x: min(x['score'], x['alt_score']))

Comments

1

min(results, key=lambda x:min(x['score'], x['alt_score']))

x needs to reference each score for the inner min() comparison.

Comments

0
results = [
  {
    "model": "short",
    "score": 34,
    "alt_score": 1
  }, 
  {
    "model": "med",
    "score": 22,
    "alt_score": 11
  }, 
  {
    "model": "tall",
    "score": 42,
    "alt_score": 90
  }, 
  {
    "model": "xtall",
    "score": 83,
    "alt_score": 15
  }, 
]

print(min(results, key=lambda x:min(x['score'],x['alt_score'])))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.