简体   繁体   English

检查dict中是否至少包含一个dict键

[英]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. 使用此代码,只有包含key1和key2的项目才会附加到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. 如果在needed_keys集和字典之间没有共享密钥,则交集仅为空。

Note that your any(...) function would work too, just not as efficiently as the set intersection option; 请注意,您的any(...)函数也可以工作,只是没有设置交集选项那么有效; perhaps you didn't realise that the any() function actually exists? 也许你没有意识到any()函数确实存在?

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 现在,您只需检查字典键和needed_keys是否至少有一个共同的项目,使用set.isdisjoint设置操作,就像这样

>>> [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. 这将非常有效,因为如果找到单个公共元素,它将立即返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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