Python – Populate a list by searching through a list of objects and seeing if they contain a specific value

Question:

I’m trying to populate a list based on specific items listed within a list of objects. I’m struggling to find the right syntax to let me search through a list of objects to see if a list contained within those objects has a specific value or not.

Here is my list of objects:

my_list = [
    {
        "name": "A",
        "group": "Upper",
        "availability": [
            "Morning",
            "Afternoon",
            "Evening",
            "Night"
        ]
    },
    {
        "name": "B",
        "group": "Upper",
        "availability": [
            "Evening",
            "Night"
        ]
    },
    {
        "name": "C",
        "group": "Lower",
        "availability": [
            "Morning"
        ]
    }
]

I want to fill a new list with the name and group of any object that has "Morning" in the "availability" list.

I’ve looked up various different ways of populating lists, but I haven’t found a way to populate a list based on whether a list within an object within a list contains a specific item.

!EDIT!
I tried using the list comprehension suggestion below and it seemed to work, but then I tried to apply it to populating my new list with both the name and group:

availability_list = [obj["name", "group"] for obj in my_list if "Morning" in obj["availability"]]

and I’m now getting the following error:

Exception has occurred: KeyError
('name', 'group')
Asked By: Moonlyte Demon

||

Answers:

You can use a list comprehension:

available_in_morning = [obj["name"] for obj in my_list if "Morning" in obj["availability"]]
Answered By: Kapocsi

Because you want both the name and the group, just create a new dictionary and then add to a list as follow:

new_list = []
for obj in my_list:
    if "Morning" in obj['availability']:
        new_dict = {'name':obj['name'],'group':obj['group']}
        new_list.append( new_dict )
print( new_list )

with the following result:

[{'name': 'A', 'group': 'Upper'}, {'name': 'C', 'group': 'Lower'}]

If you really want the inline solution here it is, but never use this if you are a real programmer in a company. Its just appalling practise for maintainability and reusability:

new_list = [ ({'name':obj['name'],'group':obj['group']}) for obj in my_list if "Morning" in obj['availability'] ]
Answered By: Eamonn Kenny
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.