Is there any better way to do this? (avoiding to systematically compare key1 and key2)
for key1 in my_dict:
for key2 in my_dict:
if key1 != key2:
#operation on my_dict[key1] and my_dict[key2]
Is there any better way to do this? (avoiding to systematically compare key1 and key2)
for key1 in my_dict:
for key2 in my_dict:
if key1 != key2:
#operation on my_dict[key1] and my_dict[key2]
You could use itertools.combinations
to get all pairs of keys:
import itertools
for k1, k2 in itertools.combinations(my_dict, 2):
This assumes that the order is not important; if it is, use itertools.permutations
:
for k1, k2 in itertools.permutations(my_dict, 2):
If key1 and key2 are keys of the same dictionary then, they are always different. On the other hand, if what you want is to perform an operation over the inner cartesian product of *my_dict* key set you could try something like:
map(lambda x: operation(x[0], x[1]), itertools.product(my_dict.keys(),my_dict.keys()))