Python 如何在没有迭代的情况下检查一个字典中的任何项是否存在于另一个字典中?
我目前正在编写的代码要求我检查一个字典中的任何项(至少一项)是否存在于另一个字典中 这个解决方案怎么样:Python 如何在没有迭代的情况下检查一个字典中的任何项是否存在于另一个字典中?,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我目前正在编写的代码要求我检查一个字典中的任何项(至少一项)是否存在于另一个字典中 这个解决方案怎么样: a = {"a":2, "b":4, "c":4, "d":4} b = {"a":1, "e":1, "f":5} print(any(a.items() & b.items())) 将产生以下产出: False 因为a和b中没有公共项,而: a = {"a":2, "b":4, "c":4, "d":4} b = {"a":1, "b":4, "f":5} print(any(
a = {"a":2, "b":4, "c":4, "d":4}
b = {"a":1, "e":1, "f":5}
print(any(a.items() & b.items()))
将产生以下产出:
False
因为a
和b
中没有公共项,而:
a = {"a":2, "b":4, "c":4, "d":4}
b = {"a":1, "b":4, "f":5}
print(any(a.items() & b.items()))
将产生以下产出:
True
因为a
和b
它不直接在字典上迭代,但是正如注释中指出的,这个解决方案在技术上使用迭代,就像在引擎盖下
any()
进行迭代一样。您可以使用set
检查第一个dict
的键和/或值中是否至少有一个存在于第二个中。您可以这样做:
[item for item in dict1.items() if item in dict2.items()]
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
使用set intersection仅使用这些数据结构,需要进行某种迭代。迭代可以推进到C中,但它会在那里。如果有任何项目需要迭代(在一些基本级别,例如集合交集将在引擎盖下进行迭代)。如果您想检查字典中是否有某个特定项,可以通过字典访问来完成……需要显示的是,键
或值
?您必须以某种方式检查元素,我同意,但OP没有重复指定,因此,您的答案至少应该说明您必须以某种方式进行迭代。