van
van

Reputation: 643

Intersection of a set and list of dictionaries

I have a set my_set = ("a","b","c","d","z") and a list my_list=[{"a",0.5},{"c",0.6},{"b",0.9},{"z",0.5},{"m",0.0}]. I would like to have a list with items containing keys in my_set only. In this case the result I would like to have is new_list=[{"a",0.5},{"c",0.6},{"b",0.9},{"z",0.5}]

The list and set is large. Is there an efficient way to accomplish this?

Upvotes: 0

Views: 41

Answers (1)

tobias_k
tobias_k

Reputation: 82899

Assuming that that's actually a set and a list of dicts, as stated in the question, you can try this:

In [1]: my_set = set(["a","b","c","d","z"])
In [2]: my_list=[{"a":0.5},{"c":0.6},{"b":0.9},{"z":0.5},{"m":0.0}]
In [3]: [d for d in my_list if all(k in my_set for k in d)]
Out[3]: [{'a': 0.5}, {'c': 0.6}, {'b': 0.9}, {'z': 0.5}]

This simply uses a list comprehension to check that all the keys in the dicts are contained in the set. This will have complexity of O(nm), for n dicts in the list, with m keys each (m being 1 in your case) and assuming that set-lookup is always O(1).

Note, however, that you do not really need a list of dictionaries, since all the keys seem to be different (in this example, at least), so a single dictionary would be enough.

Upvotes: 1

Related Questions