2

I have a dictionary of numbers, and I would like to get a list of all pairwise multiplications, excluding multiplication with itself.

test_dict = {'id_1': 8, 'id_2': 9, 'id_3': 10}
test_keys = list(test_dict.keys())
list_of_multiples = []

for i in range(0, len(test_keys)):
    count = 0
    
    if i == count:
        count += 1
        
    else:
        if count < len(test_keys):
        
            mult = (test_dict[test_keys[i]] * test_dict[test_keys[count]])
            list_of_multiples.append(mult)
            count += 1

list_of_multiples

Output: [72, 80]

Intended output: [72, 80, 72, 90, 80, 90]

I'm relatively new so the if logic has been confusing. Also if there is a pre-built function that does this, that would be good too. Thanks a lot

2 Answers2

1

What you are looking for is achieved with the most idiomatic piece of python by using a list comprehension:

keys=test_dict.keys()
list_of_multiples=[test_dict[i]*test_dict[j] for i in keys for j in keys if i!=j]

This is not necessarily obvious if you're new to python. It is a compact way of writing the following:

keys=test_dict.keys()
list_of_multiples=[]
for i in keys:
  for j in keys:
    if i != j:
      list_of_multiples.append(test_dict[i]*test_dict[j])
jfahne
  • 171
  • 7
0

Use itertools.permutations:

from itertools import permutations

test_dict = {'id_1': 8, 'id_2': 9, 'id_3': 10}

perm = list(permutations(test_dict.values(), 2))
list_of_multiples = [i[0]*i[1] for i in perm]
print(list_of_multiples)

Output:

[72, 80, 72, 90, 80, 90]
thorntonc
  • 2,046
  • 1
  • 8
  • 20