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]
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With