Search, if the values ​​in the list are specified in the dictionary, the format of which is the key line, the list of values ​​(lines)

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 create a list that will output something like this:

 output_list = ['a', 'b'] 

I need to check if the values ​​in the "list" match the values ​​in the list inside the dictionary. Is it possible?

I tried using this, but I only got an empty list:

 [key for key, value in my_dict.items() if value in list] 
+5
source share
1 answer

You also need to iterate over list (and you should not use list as the variable name, it obscures 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 values ​​in the dictionary (since searching inside a set is an O (1) operation, while 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 matches 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 the dictionary does not have a 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'] 
+4
source

Source: https://habr.com/ru/post/1232330/


All Articles