4

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]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
teaLeef
  • 1,879
  • 2
  • 16
  • 26
  • I think I need to know more about your case to give a qualified answer. What is the reason you want to do this? All keys are in a dict only once. Only instances of hashable types are allowed as keys, so also aiming of the difference between `==` and `is` probably won't make much sense. So why do you want to do this comparison, what are your keys, and what kind of comparison (`==`, `is`, ...) are you trying to perform? – Alfe Mar 21 '14 at 09:07
  • @Alfe I want to perform an operation on all the elements of a dictionary, but never on the same element – teaLeef Mar 21 '14 at 09:08
  • @Torxed I don't think that is a duplicate, the OP wants to process dictionary values pairwise, avoiding pairing the same key to itself – jonrsharpe Mar 21 '14 at 09:16
  • @jonrsharpe well, the above link will give you an object to iterate over doing the `#operation on key1 and key2` without having to check if both keys are present. You get one unified dictionary where the keys are the same, and the reversed can be achieved with the same method if you want uniqueue keys only. – Torxed Mar 21 '14 at 09:33
  • 1
    @Torxed of course both keys are present, `key1` and `key2` are *both keys in the same dictionary*. This question is about a *single dictionary*, not trying to find keys in two dictionaries. – jonrsharpe Mar 21 '14 at 10:18

2 Answers2

4

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):
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1

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()))