Home > Mobile >  how can i access conditional items in dictionary that is in a list in python?
how can i access conditional items in dictionary that is in a list in python?

Time:09-04

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)

CodePudding user response:

You can correct and improve your code as follows:

  1. Pass your data as an argument to your function rather than trying to access the global variable directly.
  2. Access each employee from your list of employees and then use the relevant keys to access the desired data e.g. employee['age']
  3. 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


result = retrieve_desired_employees(data)
print(result)

CodePudding user response:

This helps:

def function(employee):
    for value in employee:
        if value["age"] > 25 and value["Salary"] > 25000:
            empty_list.append(value)

function(employee)

But better do it with return:

def function(listof:list)->list:
    empty_list = []
    for value in listof:
        if value["age"] > 25 and value["Salary"] > 25000:
            empty_list.append(value)
    return empty_list

print(function(employee))
  • Related