Skip to content
Advertisement

Python – Pull Out Values from Only Dictionaries that Meet a Certain Criteria

I have a Python list called “results” that has dictionaries as its values:

results = [
{
 'postingStatus': 'Active', 
 'postEndDate': '1601683199000', 
 'boardId': '_internal', 
 'postStartDate': '1591084714000)'
 }, 
{
 'postingStatus': 'Expired', 
 'postEndDate': '1601683199000', 
 'boardId': '_external', 
 'postStartDate': '1591084719000)'
}
]

How would I create a list that gets all the values from the dictionary where the ‘boardID’ value is ‘_internal’ (but ignores the dictionary where ‘boardID’ is ‘_external’)? As an end result, I’m hoping for a list with the following contents:

['Active','1601683199000','_internal','1591084714000']

Advertisement

Answer

You can use list-comprehension:

out = [v for d in results for v in d.values() if d["boardId"] == "_internal"]
print(out)

Prints:

['Active', '1601683199000', '_internal', '1591084714000)']
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement