Chencheng Liu
Chencheng Liu

Reputation: 35

How to check is the value of a list of dicts is in a certain range?

I have a list of dicts like this:

list = [{'name': 'John', 'age': 24}, {'name': 'Matt', 'age': 29} , {'name': 'Peter', 'age': 40}]

I want to know if there is people whose age is between 20-30. If there is more than one person, then print the name whose age is closest to 25. The expected result would be:

{'name': 'John', 'age': 24}

But what if there is no one in the list whose age is between 20-30, the expected result would be:

{'name': None, 'age': None}

Upvotes: 0

Views: 101

Answers (2)

Jab
Jab

Reputation: 27515

A simple list comprehension will filter your data. As for finding the closest to age 25 I'd use min.

data = [{'name': 'John', 'age': 24}, {'name': 'Matt', 'age': 29} , {'name': 'Peter', 'age': 40}]

filtered = [d for d in data if 20 < d['age'] < 30]

if filtered:
    print(min(filtered, key=lambda x: abs(x['age']-25)))
else:
    print({'name': None, 'age': None})

Upvotes: 0

chepner
chepner

Reputation: 531948

I would do it in two steps, just to keep the code from becoming overly complicated.

First, get the person whose age is closest to 25. Then use that person if they are in range, or use the "empty" person.

result = min(list, key=lambda p: abs(p['age'] - 25))
result = result if 20 <= result['age'] <= 30 else dict(name=None, age=None)

In Python 3.8, you could write

result = x if 20 <= (x := min(list, key=lambda p: abs(p['age'] - 25)))['age'] <= 30 else dict(name=None, age=None)

but I wouldn't.

Upvotes: 3

Related Questions