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