python - Searching for item in two dictionaries and returning result based on the match -


co_1 = {'a1': [(1, 1)], 'b1': [(0, 4), (0, 0), (4, 0)]} co_2 = {'a2': [(2, 2)], 'b2': [(1, 5), (1, 2), (5, 1)]}  position = (x, y) 

how check if position(e.g. (1, 5)) present in values of 2 dictionaries 'co_1 , co_2'.

so far have:

for key, value in co_1.items():     if position in value:         return (statement1) key, value in co_1.items():     if position in value:         return(statement2) #if position not in either value --> return none 

is there way clean can search position in both dictionaries , have if-else statement: if position present in values (co_1 or co_2) return (statement) else return none.

such as:

for key, value in co_1.items() , co_2.items():     if position in value in co_1.items():         return statement1     elif position in value in co_2.items():         return statement2     else:         return none #example if position = (2, 2) --> return statement2 #exmaple if position = (3, 1) --> return none 

it seems keys not relevant here – build set of tuples both dictionaries.

co_1_set = {y x in co_1 y in co_1[x] }  co_2_set = {y x in co_2 y in co_2[x] }  

now, membership test simple if-elif statement:

def foo(position):     if position in co_1_set:         return statement1      elif position in co_2_set:         return statement2 

you'll want perform set constructions little possible - ideally when dictionary contents change.


if both dictionaries contain position, code returns statement1 only. if want different, you'll need make changes appropriate.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -