Lesson 7
Objects and Dictionaries
Chapter 5: Application of dictionaries
Filtering the employees
Now let us do something with the list of employees you have loaded from the previous task!
Again, this is a continuation from the previous task, so you can again work with the same source file as the load_employees()
function earlier.
Now, write another function called filter_employees()
. It should take two input arguments:
- a
list
of employees, where each element is adict
with the keysid
,name
,age
andnationality
(the same as the expected return value ofload_employees()
) - a
tuple
representing an (attribute
,value
) pair.
The function should return a list
of employees (the same format as the first input argument), but with the elements filtered to only retain those that match the (attribute
, value
) pair given as the second input argument.
See the sample usage below for some examples.
Sample usage
>>> employees = [{"id": "111", "name": "Joe", "age": 24},
... {"id": "222", "name": "Luca", "age": 26},
... {"id": "333", "name": "Harry", "age": 24},
... {"id": "444", "name": "William", "age": 23}
... ]
...
>>> filtered_employees = filter_employees(employees, ("age", 24))
>>> print(filtered_employees)
[{'id': '111', 'name': 'Joe', 'age': 24}, {'id': '333', 'name': 'Harry', 'age': 24}]
>>> employees = load_employees("employees_detail.txt")
>>> criterion = ("nationality", "portugal")
>>> filtered_employees = filter_employees(employees, criterion)
>>> print(filtered_employees)
[{'id': '82660090', 'name': 'Meri Chaudhary', 'age': 40, 'nationality': 'portugal'},
{'id': '54835190', 'name': 'Neelima Voll', 'age': 37, 'nationality': 'portugal'}]