Home > Software engineering >  Dictionary with multiple values per key via for loop
Dictionary with multiple values per key via for loop

Time:10-21

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.

Does anyone know if there exists a solution?

CodePudding user response:

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)]}

CodePudding user response:

Try this:

arr = [1, 0, -1, 0]

map = {}

for i in range(len(arr)):
    for j in range(i   1, len(arr)):
        s = arr[i]   arr[j]
        if s not in map:
            map[s] = []
        map[s].append((i, j))

print(map)
  • Related