Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)

my_dict = {                              # This dictionary is generated thru
'a' : [ 'value1', 'value4', 'value5' ],  # the info given by the user
'b' : [ 'value2', 'value6', 'value7'],
'c' : [ 'value3', 'value8', 'value9']
}

list = [ 'value1', 'value2' ] # List is generated using list comprehension

I need to generate a list that will output something like this:

output_list = ['a', 'b']

I need to check if the values on "list" matches with the values on the list inside of the dictionary. Is this even possible?

I tried to use this but I only get an empty list:

[key for key, value in my_dict.items() if value in list]
like image 215
Juan dela Cruz Avatar asked Sep 27 '22 15:09

Juan dela Cruz


1 Answers

You need to iterate over the list as well (and you should not be using list as a variable name, it shadows the built-in list function) . Example -

[key for item in lst for key,value in my_dict.items() if item in value]

Demo -

>>> my_dict = {                              # This dictionary is generated thru
... 'a' : [ 'value1', 'value4', 'value5' ],  # the info given by the user
... 'b' : [ 'value2', 'value6', 'value7'],
... 'c' : [ 'value3', 'value8', 'value9']
... }
>>>
>>> lst = [ 'value1', 'value2' ]
>>> [key for item in lst for key,value in my_dict.items() if item in value]
['a', 'b']

You can get better performance, if you use set instead of list to store the values in the dictionary (since searching inside a set is O(1) operation, whereas searching inside a list is O(n) ). Example -

my_dict = {key:set(value) for key,value in my_dict.items()}
[key for item in lst for key,value in my_dict.items() if item in value]

Demo -

>>> my_dict = {key:set(value) for key,value in my_dict.items()}
>>> pprint(my_dict)
{'a': {'value4', 'value5', 'value1'},
 'b': {'value6', 'value7', 'value2'},
 'c': {'value3', 'value9', 'value8'}}
>>> lst = [ 'value1', 'value2' ]
>>> [key for item in lst for key,value in my_dict.items() if item in value]
['a', 'b']

If you are trying to check if any of the values in the list match with any value from the list in the dictionary, you can use set.intersection and check if the result is empty or not. Example -

[key for key, value in my_dict.items() if set(value).intersection(lst)]

This result will not be ordered, since dictionary does not have any specific order.

Demo -

>>> my_dict = {
... 'a' : [ 'value1', 'value4', 'value5' ],
... 'b' : [ 'value2', 'value6', 'value7'],
... 'c' : [ 'value3', 'value8', 'value9']
... }
>>> lst = [ 'value1', 'value2' ]
>>> [key for key, value in my_dict.items() if set(value).intersection(lst)]
['b', 'a']
like image 97
Anand S Kumar Avatar answered Oct 11 '22 11:10

Anand S Kumar