Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python find dictionaries in list where certain key is not present

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"])) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading