Home > Blockchain >  List comprehension with if statement for a list of dictionary
List comprehension with if statement for a list of dictionary

Time:11-09

I am learning about list comprehension, and trying to solve an exercise but I am stuck with the right index and arguments. So I have this list of dictionary called 'people', and I need to create a function with 2 arguments (first one, a list of dictionary, like 'people', and the other one, 'minimum_age' with default value of 18 if the argument is not specified) that needs to return a new list which includes only the people above the minimum_age. If the age value is not specified, that person shall be excluded. I would need to solve this with list comprehension.

       people = [{"name": "John", "age": 12}, {"name": "Sam", "age": 36}, {"name": "Frank"}
       def function(people, minimum_age=18):       
       new_list = 
       return new_list 

Many thanks in advance for your help!

CodePudding user response:

def function(people, minimum_age=18):       
    return [person for person in people if 'age' in person and person['age'] >= minimum_age]

CodePudding user response:

The basic idea is to do a regular list-comprehension, but if you don't always have the age then you should put an absurdly small default age in the condition clause:

people = [{"name": "John", "age": 12}, {"name": "Sam", "age": 36}, {"name": "Frank"}]
def function(people, minimum_age=18):       
   new_list = [p for p in people if p.get('age', -10000) >= minimum_age] 
   return new_list 

print(function(people))

If you don't want to assume a specific "minimal" age then you can use numpy and have the default value set to -np.inf.

Note, that the list-comprehension is just short-hand for an explicit loop, which would look like this:

people = [{"name": "John", "age": 12}, {"name": "Sam", "age": 36}, {"name": "Frank"}]
def function(people, minimum_age=18): 
    new_list = []
    for p in people:
        if p.get('age', -10000) >= minimum_age:
            new_list.append(p)
    return new_list
      
print(function(people))
  • Related