Home > Software design >  python find dictionaries in list where certain key is not present
python find dictionaries in list where certain key is not present

Time:07-21

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?

CodePudding user response:

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

CodePudding user response:

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).

  • Related