python - Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings) -
my_dict = { # dictionary generated thru 'a' : [ 'value1', 'value4', 'value5' ], # info given user 'b' : [ 'value2', 'value6', 'value7'], 'c' : [ 'value3', 'value8', 'value9'] } list = [ 'value1', 'value2' ] # list generated using list comprehension
i need generate list output this:
output_list = ['a', 'b']
i need check if values on "list" matches values on list inside of dictionary. possible?
i tried use empty list:
[key key, value in my_dict.items() if value in list]
you need iterate on list
(and should not using list
variable name, shadows built-in list
function) . example -
[key item in lst key,value in my_dict.items() if item in value]
demo -
>>> my_dict = { # dictionary generated thru ... 'a' : [ 'value1', 'value4', 'value5' ], # info given user ... 'b' : [ 'value2', 'value6', 'value7'], ... 'c' : [ 'value3', 'value8', 'value9'] ... } >>> >>> lst = [ 'value1', 'value2' ] >>> [key item in lst key,value in my_dict.items() if item in value] ['a', 'b']
you can better performance, if use set
instead of list
store values in dictionary (since searching inside set o(1) operation, whereas searching inside list o(n) ). example -
my_dict = {key:set(value) key,value in my_dict.items()} [key item in lst key,value in my_dict.items() if item in value]
demo -
>>> my_dict = {key:set(value) 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 item in lst key,value in my_dict.items() if item in value] ['a', 'b']
if trying check if of values in list match value list in dictionary, can use set.intersection
, check if result empty or not. example -
[key key, value in my_dict.items() if set(value).intersection(lst)]
this result not ordered, since dictionary not have specific order.
demo -
>>> my_dict = { ... 'a' : [ 'value1', 'value4', 'value5' ], ... 'b' : [ 'value2', 'value6', 'value7'], ... 'c' : [ 'value3', 'value8', 'value9'] ... } >>> lst = [ 'value1', 'value2' ] >>> [key key, value in my_dict.items() if set(value).intersection(lst)] ['b', 'a']
Comments
Post a Comment