Dictionaries python


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}
Asked By: Ayesha



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

this will print

{('am', 'and'): 2}
Answered By: Selcuk