Issue
empty_list=[]
employee = [{
"name" : "Nauman",
"age" : 27,
"Salary": 29000
},
{
"name": "Bilal",
"age": 26,
"Salary": 27000
},
{
"name": "Ali",
"age": 19,
"Salary": 22000
},
{
"name": "Usman",
"age": 28,
"Salary": 34000
},
{
"name": "Usama",
"age": 14,
"Salary": 24000
}
]
def function(employee):
for value in employee:
if employee.my_dict(["age"])>25 and employee.my_dict(["salary"])>25000:
empty_list.append(employee)
print(empty_list)
Solution
You can correct and improve your code as follows:
- Pass your data as an argument to your function rather than trying to access the global variable directly.
- Access each employee from your list of employees and then use the relevant keys to access the desired data e.g.
employee['age']
- Your function can return the result containing the employees that meet the specified conditions. This then allows you to invoke the function as and when desired.
Here is an example solution that follows the above corrections/recommendations:
data = [
{
"name" : "Nauman",
"age" : 27,
"salary": 29000
},
{
"name": "Bilal",
"age": 26,
"salary": 27000
},
{
"name": "Ali",
"age": 19,
"salary": 22000
},
{
"name": "Usman",
"age": 28,
"salary": 34000
},
{
"name": "Usama",
"age": 14,
"salary": 24000
}]
def retrieve_desired_employees(employees):
result = []
for employee in employees:
if employee['age'] > 25 and employee['salary'] > 25000:
result.append(employee)
return result
print(retrieve_desired_employees(data))
If the keys age
and salary
are not guaranteed to be in the dictionaries then you can use the dictionary's get
method to supply a default value.
Here is a modified example:
def retrieve_desired_employees(employees):
result = []
for employee in employees:
if employee.get('age', 0) > 25 and employee.get('salary', 0) > 25000:
result.append(employee)
return result
Answered By - Prins
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.