繁体   English   中英

如何检查一个字典中是否有任何项目存在于另一个字典中而不进行迭代?

[英]How to check if any item in one dictionary is present in another dictionary without iteration?

目前,我正在编写的代码要求我检查一本词典中是否有任何项目(至少一项)存在于另一本词典中。

该解决方案如何:

a = {"a":2, "b":4, "c":4, "d":4}
b = {"a":1, "e":1, "f":5}
print(any(a.items() & b.items()))

将产生输出: False

因为ab没有共同的项目,而:

a = {"a":2, "b":4, "c":4, "d":4}
b = {"a":1, "b":4, "f":5}
print(any(a.items() & b.items()))

将产生输出: True

因为ab有一个共同的项目

它不会直接对字典进行迭代,但是正如juanpa-arrivillaga在评论中指出的那样,该解决方案在技术上使用了迭代,就像在any()迭代一样。

[item for item in dict1.items() if item in dict2.items()]

您可以使用set检查第二个dict是否至少有第一个dict的键和/或值之一。 您可以执行以下操作:

a = {1:"a", 2:"b", 3:"c"}
b = {"foo":"hello", "bar":"hi", 2:"hoo"}
c = {"hello":"hoo", 1:"hii"}

def keys_exists(first:"dict", second:"dict") -> bool:
    # Or:
    # return not (set(first) - set(second)) == first.keys()
    return bool(set(first) & set(second))

def values_exists(first:"dict", second:"dict") -> bool:
    return bool(set(first.values()) & set(second.values()))


print("At least one of a keys exists in b keys: {0}".format(keys_exists(a,b)))
print("At least one of a keys exists in c keys: {0}".format(keys_exists(a,c)))
print("At least one of b keys exists in c keys: {0}".format(keys_exists(b,c)))

print("At least one of a values exists in b values: {0}".format(values_exists(a,b)))
print("At least one of a values exists in c values: {0}".format(values_exists(a,c)))
print("At least one of b values exists in c values: {0}".format(values_exists(b,c)))

输出:

At least one of a keys exists in b keys: True
At least one of a keys exists in c keys: True
At least one of b keys exists in c keys: False

At least one of a values exists in b values: False
At least one of a values exists in c values: False
At least one of b values exists in c values: True

暂无
暂无

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

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