简体   繁体   中英

Check if at least one key of dict is contained in another dict

I want to check if at least one key from a given dict is available in another dict. I already know how to check for "must"-keys like this:

valid_data = []
needed_keys = (key1, key2)

for d in data:
    if not all(key in d for key in needed_keys):
        continue  # ignore invalid object

    valid_data.append(d)

data is here a list of dicts. With this code only items which contain both, key1 and key2 are appended to valid_data.

Is there something like:

if not any(key in d for key in needed_keys)

which also succeeds if any key from the needed keys is available?

Use set intersections :

needed_keys = {key1, key2}

for d in data:
    if needed_keys.intersection(d):
        valid_data.append(d)

The intersection is only empty if no keys are shared between the needed_keys set and the dictionary.

Note that your any(...) function would work too, just not as efficiently as the set intersection option; perhaps you didn't realise that the any() function actually exists?

Lets say your data is like this

>>> d1, d2 = {"a" : 1, "b" : 2, "c" : 3}, {"b" : 1, "c" : 2, "d" : 3}

First, define the needed keys as a set. Lets say,

>>> needed_keys = {"a", "b", "d"}

Now, you can simply check if both the dictionary keys and the needed_keys have atleast one item in common, with set.isdisjoint set operation, like this

>>> [item for item in (d1, d2) if not needed_keys.isdisjoint(item)]

This will be very efficient, since it will return immediately if it finds a single common element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM