I have an array of objects like below:
JavaScript
x
7
1
my_objects = [
2
{"id": 1, "labels": {"abc": "123"}},
3
{"id": 2, "labels": {"prefix-abc": "123"}},
4
{"id": 3, "labels": {"prefix-abc": "123"}},
5
{"id": 4, "labels": {"xyz-abc": "123"}},
6
]
7
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:
JavaScript
1
5
1
filtered = [
2
{"id": 1, "labels": {"abc": "123"}},
3
{"id": 4, "labels": {"xyz-abc": "123"}},
4
]
5
At the moment I have a working solution but not sure if its the most efficient:
JavaScript
1
6
1
for thing in my_objects:
2
labels = thing.get("labels", {})
3
for key in labels.keys():
4
if "prefix-" in key:
5
# handle
6
Advertisement
Answer
Here is a possible solution:
JavaScript
1
3
1
filtered = [obj for obj in my_objects
2
if not any(lab.startswith('prefix-') for lab in obj['labels'])]
3