Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dictionary with multiple values per key via for loop

given a List in Python I want top create a dictionary that stores all possible two sums as keys and the corresponding indices as values, e.g.

list = [1,0,-1, 0]
Then I would to compute the dictionary {1:{0,1}, {0,3}, 0: {1,3},{0,2}, -1:{1,2}, {2,3}}.

I am having troubles finding out how to have a dictionary where one key corresponds to multiple values. If I use dict[sum]={i,j} I am always replacing the entries in my dictionary while instead I would like to add them.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone know if there exists a solution?

>Solution :

IIUC, use a dictionary with setdefault to add the results and itertools.combinations to generate the combinations of indices:

lst = [1,0,-1, 0]

from itertools import combinations

out = {}
for i,j in combinations(range(len(lst)), 2):
    a = lst[i]  # first value
    b = lst[j]  # second value
    S = a+b     # sum of values
    # if the key is missing, add empty list
    # append combination of indices as value
    out.setdefault(S, []).append((i,j))

print(out)

Condensed variant:

out = {}
for i,j in combinations(range(len(lst)), 2):
    out.setdefault(lst[i]+lst[j], []).append((i,j))

output:

{ 1: [(0, 1), (0, 3)],
  0: [(0, 2), (1, 3)],
 -1: [(1, 2), (2, 3)]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading