如果两个字典中的列表元素共享任何元组,则获取键值

Get the key value if the list element in two dicts shares any tuple

我有两部词典(ab)。

每个都有许多键,列表长度不同。每个列表都有多个元组。

如果对应列表与b有任何共享元组,而不管b的键值如何,有没有快速获取a键的方法?

示例如下:

b = {41: [(37, 15), (36, 17), (36, 16), (35, 16), (36, 15)],
     42: [(40, 15), (44, 15), (40, 18), (44, 16)]}
a = {38: [(36, 18), (37, 15), (35, 16)],
     39: [(57, 0), (54, 0), (55, 0), (56, 0)]}

def test_overlap(a, b):
    overlap = frozenset(b).isdisjoint(a)
    return not overlap

list_remove = []
for id_b, b_i in b.items():
    for id_a, a_i in a.items():
        if test_overlap(a[id_a], b[id_b]):
            list_remove.append(id_a)

list_remove=list(set(list_remove))
print(list_remove)

# Output: [38]

b 中的所有元组中创建一个集合,并用它来过滤 a 中的项目:

b = {41: [(37, 15), (36, 17), (36, 16), (35, 16), (36, 15)],
     42: [(40, 15), (44, 15), (40, 18), (44, 16)]}
a = {38: [(36, 18), (37, 15), (35, 16)],
     39: [(57, 0), (54, 0), (55, 0), (56, 0)]}

tb = set().union(*b.values())
r  = [ka for ka,ta in a.items() if not tb.isdisjoint(ta)]

print(r) # [38]