I have a JSON string which I parse into a list of dictionaries.
o='{"a": [{"a_a": "123-1", "a_b": "exists"}, {"a_a": "123-2"}, {"a_a": "123-3"}]}'
o=json.loads(o)
What would be the best way now to get the dictionaries where a_b is not present?
>Solution :
One approach, using a list comprehension:
res = [d for d in o["a"] if "a_b" not in d]
print(res)
Output
[{'a_a': '123-2'}, {'a_a': '123-3'}]
Or the equivalent, less pythonic, for-loop:
res = []
for d in o["a"]:
if "a_b" not in d:
res.append(d)
A third approach, even less pythonic (in my opinion), is to use filter with a lambda function:
res = list(filter(lambda x: "a_b" not in x, o["a"]))