Home > Back-end >  How to check if a name is in a dictionary when the values are lists of names
How to check if a name is in a dictionary when the values are lists of names

Time:05-28

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)

CodePudding user response:

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

CodePudding user response:

Iterate over a dict key value with .items(), then fix the variable 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']]]

Could do it another way, maybe nicer

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())
  • Related