Reputation: 17
I was trying to compare a list with dictionary values to see if they match so I could return the key, but I couldn't find a solution to match them:
>>> my_dict = {'A': ['apple', 'america'], B: ['bee', 'bar'], C: ['car','cake','cat'], D: ['dad']}
>>> my_list = ['apple', 'dad']
In this case, the result would be:
['A', 'D']
What would be the best approach? I tried a nested for-loop, but I was wondering if there is a more direct answer.
my_second_dict = {}
for key in my_dict.keys():
for values in my_dict[key]:
I am not really sure how to do it. I'd appreciate your help.
Thanks!
Upvotes: 0
Views: 48
Reputation: 1075
I think if you finish your loop, you can end up with something like this:
output = []
for i in my_list:
for k, v in my_dict.items():
if i in v:
output.append(k)
or a one-liner
output = [k for i in my_list for k, v in my_dict.items() if i in v]
Upvotes: 0
Reputation: 543
Do you mean something like this?
my_dict = {'A': ['apple', 'america'], B: ['bee', 'bar'], C: ['car','cake','cat'], D: ['dad']}
my_list = ['apple', 'dad']
results = []
for key in my_dict.keys():
for value in my_list:
if value in my_dict[key]:
results.append(key)
break
print(results)
Loop through the keys in the dictionary, and check if any of the values in the list are in the dictionary.
You do not need to use the break statement if you use set intersection or list comprehension.
my_dict = {'A': ['apple', 'america'], B: ['bee', 'bar'], C: ['car','cake','cat'], D: ['dad']}
my_list = ['apple', 'dad']
results = []
for key in my_dict.keys():
if set(my_list).intersection(set(dict[key])):
results.append(key)
print(results)
my_dict = {'A': ['apple', 'america'], B: ['bee', 'bar'], C: ['car','cake','cat'], D: ['dad']}
my_list = ['apple', 'dad']
results = []
for key in my_dict.keys():
if any([val in my_dict[key] for val in my_list]):
results.append(key)
print(results)
Upvotes: 0
Reputation: 31319
You have a list of values and you want the keys of the dictionary items that have those values in their values (which are lists of values). This is assuming there are no duplicates in the lists in the dictionary (which seems reasonable, since it appears to group them by initial).
This is a solution:
my_dict = {'A': ['apple', 'america'], 'B': ['bee', 'bar'], 'C': ['car','cake','cat'], 'D': ['dad']}
my_list = ['apple', 'dad']
my_result = [k for v in my_list for k, vs in my_dict.items() if v in vs]
print(my_result)
Result:
['A', 'D']
Upvotes: 1