Blob
Blob

Reputation: 381

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?

Upvotes: 0

Views: 45

Answers (2)

mozway
mozway

Reputation: 260815

You can use a list comprehension, as there could be several matches, the output is a list:

out = [d for d in o['a'] if 'a_b' not in d]

Output: [{'a_a': '123-1', 'a_b': 'exists'}]

If you expect at most one match (or only care about the first one):

next((d for d in o['a'] if 'a_b' not in d), None)

Output: {'a_a': '123-2'}

NB. You can also use another default value in next (not necessarily None).

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

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"])) 

Upvotes: 1

Related Questions