Home > Enterprise >  Filter all dicts in a list to be with specific keys and ignore others?
Filter all dicts in a list to be with specific keys and ignore others?

Time:12-03

I have the following list of dicts:

lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]

I want to filter the list of dicts (in my case it's a list of thousands or even more dicts, with different keys with some overlap) to be a list containing all the dicts that have keys: ["a", "b"]. I want to filter each dict only to these a and b keys, and if they don't exist, don't include the dictionary in the final list. I am using:

[{"a": d.get("a"), "b": d.get("b")} for d in lst]

Please advise for an elegant way to solve it.

CodePudding user response:

The dictionary keys-view is set-like, so it supports subset comparisons by using <= operator:

>>> keys = set("ab")
>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]
[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]

CodePudding user response:

I have figured it out and here is my alternative:

lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
keys = set("ab")
[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]

Gives the desired answer:

[{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]
  • Related