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.
JavaScript
x
6
1
name_types = {'Protocol': ['a', 'b', 'c'], 'Tech': ['a', 'b', 'd']}
2
names = ['a', 'b', 'c', 'd']
3
4
# Goal
5
result[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['None']], ['d', ['Tech']]]
6
I tried something like this, but I got too many values to unpack error:
JavaScript
1
11
11
1
result = []
2
3
for n in names:
4
list_types = []
5
for key, list_names in name_types:
6
if d in list_names:
7
list_types.append(key)
8
result.append(d, list_types)
9
10
print(result)
11
Advertisement
Answer
Your data and result don’t match (‘c’ is a ‘Protocol’). I’ve removed ‘c’ to match the desired result:
JavaScript
1
15
15
1
name_types = {'Protocol': ['a', 'b'], 'Tech': ['a', 'b', 'd']}
2
names = ['a', 'b', 'c', 'd']
3
4
result = []
5
for name in names:
6
current = [name,[]]
7
for k,v in name_types.items():
8
if name in v:
9
current[1].append(k)
10
if not current[1]:
11
current[1].append('None')
12
result.append(current)
13
14
print(result)
15
Output:
JavaScript
1
2
1
[['a', ['Protocol', 'Tech']], ['b', ['Protocol', 'Tech']], ['c', ['None']], ['d', ['Tech']]]
2