Home > Software design >  Remove single value from list of dictionaries
Remove single value from list of dictionaries

Time:09-21

I have a list of dictionaries as data input. I also have a function that I want to iterate and remove single dictionaries (i.e. remove Pippin) based on the 'type' key so that he is not counted as a potential option in further iterations looking for an 'Uncertified Installer'.

Is this possible? Code below.

List of dictionaries

employees=[
    {
        'name':'Pippin',
        'type':'Uncertified Installer',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Merry',
        'type':'Handyperson',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Sam',
        'type':'Handyperson',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Frodo',
        'type':'Uncertified Installer',
        'days_available':['M','Tu','W','Th','F']
    }

Function so far

def schedule(buildings, employees):

        for building in buildings:
            remaining_employee_list=employees.copy()
            
            if building == 'single':
                remaining_employee_list[:]=[d for d in employees if (d.get('type')!='Handyperson') and (d.get('type')!='Uncertified Installer')]
                buildings.remove('single')
                
                print(building, remaining_employee_list)

CodePudding user response:

List comprehensions is likely the easiest and most idiomatic way of doing this:

employees = [
    {
        "name": "Pippin",
        "type": "Uncertified Installer",
        "days_available": ["M", "Tu", "W", "Th", "F"],
    },
    {
        "name": "Merry",
        "type": "Handyperson",
        "days_available": ["M", "Tu", "W", "Th", "F"],
    },
]

certified_employees = [
    employee
    for employee in employees
    if employee.get("type") != "Uncertified Installer" # here one could add additional conditions (for example a check on the building object)
]

CodePudding user response:

How about this:-

employees=[
    {
        'name':'Pippin',
        'type':'Uncertified Installer',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Merry',
        'type':'Handyperson',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Sam',
        'type':'Handyperson',
        'days_available':['M','Tu','W','Th','F']
    },
    {
        'name':'Frodo',
        'type':'Uncertified Installer',
        'days_available':['M','Tu','W','Th','F']
    }]

UI = 'Uncertified Installer'
E = [d for d in employees if d.get('type', UI) != UI]
print(E)
  • Related