我写的代码目前要求我检查一个词典中是否有任何项目(至少一个)存在于另一个词典中。
答案 0 :(得分:1)
这个解决方案怎么样:
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
它不会直接迭代字典,但正如juanpa-arrivillaga在评论中指出的那样,此解决方案在技术上使用迭代,因为在any()
下进行迭代。
答案 1 :(得分:0)
[item for item in dict1.items() if item in dict2.items()]
答案 2 :(得分:0)
您可以使用set
检查第二个中是否存在至少一个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