简体   繁体   中英

How to access conditional items in dictionary that is in a list

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)

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

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 eg 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)
def get_empty_list(employees):
    return [employee for employee in employees if employee["age"]>25 and employee["Salary"]>25000]

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