Skip to content
Advertisement

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

I have a list of names, and I am trying to loop through that list and see if a name is a value in the name_types dictionary, and if it is then I want to add the name to a results list with a list of the name types that it belongs to, however, I am not sure about how to do this. Also, I want to store None if it is not a part of any.

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']]]  

I tried something like this, but I got too many values to unpack error:

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)

Advertisement

Answer

Your data and result don’t match (‘c’ is a ‘Protocol’). I’ve removed ‘c’ to match the desired result:

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)

Output:

[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['None']], ['d', ['Tech']]]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement