I have an array of objects like below:
my_objects = [ {"id": 1, "labels": {"abc": "123"}}, {"id": 2, "labels": {"prefix-abc": "123"}}, {"id": 3, "labels": {"prefix-abc": "123"}}, {"id": 4, "labels": {"xyz-abc": "123"}}, ]
I want to be able to filter down to objects that don’t have a key in labels that match prefix-
.
What I’d end up with is:
filtered = [ {"id": 1, "labels": {"abc": "123"}}, {"id": 4, "labels": {"xyz-abc": "123"}}, ]
At the moment I have a working solution but not sure if its the most efficient:
for thing in my_objects: labels = thing.get("labels", {}) for key in labels.keys(): if "prefix-" in key: # handle
Advertisement
Answer
Here is a possible solution:
filtered = [obj for obj in my_objects if not any(lab.startswith('prefix-') for lab in obj['labels'])]