How to get all possible pairs in a dictionary

31 Views Asked by At

My code

I am trying to compute the dot product of 2 vectors in Python to ultimately calculate cosine similarity.

When it coms to computing the dot product, I'm creating a separate dictionary to store the dot product of each pair of words. Take ('danced', 'sang') as an example.

Both appear to be keys in the vectors dictionary, but when I try to get all pairs of words in the vectors dictionary, the ('danced', 'sang') pair doesn't seem to exist in the dot_products dictionary. Am I doing something wrong when it comes to getting all possible pairs? I would imagine that that would have to be done with nested loops, no?

1

There are 1 best solutions below

1
CodeForest On

Here's a basic outline of how you can compute the dot product for each pair of words and store the results in a dictionary:

# Assume 'vectors' is a pre-populated dictionary of word vectors
vectors = {
    'danced': [...],  # vector for 'danced'
    'sang': [...],    # vector for 'sang'
    # ... other word vectors
}

# Initialize an empty dictionary to store the dot products
dot_products = {}

# Compute the dot product for each pair of words
for word1 in vectors:
    for word2 in vectors:
        if word1 == word2:  # Skip the same word comparison
            continue
        pair = tuple(sorted((word1, word2)))  # Sort the tuple to avoid duplicates like ('sang', 'danced')
        if pair not in dot_products:
            dot_product = sum(a*b for a, b in zip(vectors[word1], vectors[word2]))
            dot_products[pair] = dot_product

# Now you can access the dot product of any pair, such as ('danced', 'sang')
print(dot_products[('danced', 'sang')])