-4

I am making a dictionary , keys having 2 words. Suppose I have two items in the dictionary:

{('am', 'and'): 1, ('and', 'am'): 1}

How to identify those above 2 keys are equal (they are just in different order).

for word1 in window:
    for word2 in window:
        if word1 != word2:
            word_pair_freq[(word1, word2)] += 1

I want the result

{('am', 'and'): 2}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
Ayesha
  • 53
  • 7
  • Does this answer your question? [how to ignore the order of elements in a tuple](https://stackoverflow.com/questions/36755714/how-to-ignore-the-order-of-elements-in-a-tuple) – Pranav Hosangadi Jan 30 '23 at 04:22

1 Answers1

0

You can sort the tuples to detect duplicate pairs:

my_dict = {('am', 'and'): 1, ('and', 'am'): 1}
word_pair_freq = {}
for words, value in my_dict.items():
    key = tuple(sorted(words))
    word_pair_freq[key] = word_pair_freq.get(key, 0) + value
print(word_pair_freq)

this will print

{('am', 'and'): 2}
Selcuk
  • 57,004
  • 12
  • 102
  • 110