简体   繁体   中英

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}

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.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM