What is the Pythonic way to iterate over set intersection and exclusions?

421 views Asked by At

set_of_A_key and set_of_B_keyare two set of keys of dictionary dict_A and dict_B. I want operate over the dictionary values for the keys in the following three sets:

(set_of_A_key & set_of_B_key), (set_of_A_key - set_of_B_key) and (set_of_B_key - set_of_A_key)

What is the pythonic way to do this?

This one is elegant with very little code repetition, but does extra computation for find the key in set intersection and exclusions

only_A = (set_of_A_key - set_of_B_key)
only_B = (set_of_B_key - set_of_A_key)

for key in (set_of_A_key | set_of_B_key):
    if key in only_A:
        A_val = dict_A[key]
        B_val = 0
    elif key in only_B:
        B_val = dict_B[key]
        A_val = 0
    else:
        B_val = dict_B[key]
        A_val = dict_A[key]
    some_function(A_val,B_val)

or this one faster but code repetition is present

for key in (set_of_A_key - set_of_B_key):
     some_function(dict_A[key],0) 
for key in (set_of_B_key - set_of_A_key):
     some_function(0,dict_B[key]) 
for key in (set_of_A_key & set_of_B_key):
     some_function(dict_A[key],dict_B[key])

or is there a better way to above?

1

There are 1 answers

1
Martijn Pieters On BEST ANSWER

You are making it way too complicated for yourself. You appear to be creating default values for missing keys, so the following is far simpler:

for key in dict_A.viewkeys() | dict_A.viewkeys():
    some_function(dict_A.get(key, 0), dict_B.get(key, 0))

using the dict.get() function to substitute a default for a missing key.

Note that I used the dict.viewkey() dictionary view to provide the set here. If you are using Python 3, then dict.keys() is a dictionary view already; dictionary views act as sets.