当值是名称列表时如何检查名称是否在字典中

How to check if a name is in a dictionary when the values are lists of names

我有一个名字列表,我试图遍历该列表并查看某个名字是否是 name_types 字典中的一个值,如果是,那么我想将该名字添加到一个结果列表,其中包含它所属的名称类型列表,但是,我不确定如何执行此操作。另外,如果它不是任何的一部分,我想存储 None。

name_types = {'Protocol': ['a', 'b', 'c'], 'Tech': ['a', 'b', 'd']}
names = ['a', 'b', 'c', 'd']

# Goal
result[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['None']], ['d', ['Tech']]]  

我试过类似的方法,但我得到的值太多无法解包错误:

result = []

for n in names:
    list_types = []
    for key, list_names in name_types:
        if d in list_names:
            list_types.append(key)
    result.append(d, list_types)

print(result)

.items()遍历字典键+值,然后修复变量d => n

for n in names:
    list_types = []
    for key, list_names in name_types.items():
        if n in list_names:
            list_types.append(key)
    result.append([n, list_types])

[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['Protocol']], ['d', ['Tech']]]

可以换一种方式,也许更好

result = {name: [] for name in names}
for key, list_names in name_types.items():
    for name in list_names:
        result[name].append(key)
print(result.items())

您的数据和结果不匹配('c' 是 'Protocol')。我已删除 'c' 以匹配所需的结果:

name_types = {'Protocol': ['a', 'b'], 'Tech': ['a', 'b', 'd']}
names = ['a', 'b', 'c', 'd']

result = []
for name in names:
    current = [name,[]]
    for k,v in name_types.items():
        if name in v:
            current[1].append(k)
    if not current[1]:
        current[1].append('None')
    result.append(current)

print(result)

输出:

[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['None']], ['d', ['Tech']]]