Ludovica
Ludovica

Reputation: 17

I would like to append different values to a dictionary with multiple keys

I have my array with data referring to different subjects divided in 3 different groups

A = ([12, 13, 15], [13, 16, 18], [15, 15, 17])

I want to append these to 3 different arrays, but I don't want to do it "manually" since I should use this code for bigger set of data. So, I was looking for a way to create as many arrays as the amount of subjects (in this case 3) assigning to them different "names".

Looking on this site I ended up using a dictionary and this is what I did

number_of_groups = len(A)
groups = {"group" + str(i+1) : [] for i in range(number_of_groups)}

and this is the output:

{'group1': [], 'group2': [], 'group3': []}

now I wasn't able to append to each of them the 3 different set of data. I expect to have:

{'group1': [12, 13, 15], 'group2': [13, 16, 18], 'group3': [15, 15, 17]}

I tried this (I know is not a good way to do it...)

for n in A:
    for key in paths: paths[key].append(n)

output:

{'group1': [array([12,  13, 15]),array([13, 16, 18]),array([15, 15, 17])],
'group2': [array([12,  13, 15]),array([13, 16, 18]),array([15, 15, 17])],
'group3': [array([12,  13, 15]),array([13, 16, 18]),array([15, 15, 17])]}

Upvotes: 1

Views: 68

Answers (2)

Manfred
Manfred

Reputation: 3142

I'mahdi had already suggested dict-comprehension to build the correct list in first place. In addition, you can use enumerate to iterate all elements a with index i of the tuple A:

groups = {
    f"group{i+1}": a
    for i, a in enumerate(A)
}

As Rolf of Saxony pointed out, enumerate has an optional start parameter for the iteration index, so you can simplify this further to:

groups = {
    f"group{i}": a
    for i, a in enumerate(A, 1)
}

Upvotes: 1

Siyana Pavlova
Siyana Pavlova

Reputation: 63

The issue is that you have a nested loop. The outer one iterates over each group, then the inner one appends each group. To edit your current code, you can try using zip() like this:

for n, key in zip(A, paths):
    paths[key].append(n)

However, since you are already using a dictionary comprehension earlier, it is definitely easier to modify that and fill the dictionary at that step already instead of first creating it and then filling it. The following outputs what you need:

groups = {"group" + str(i+1) : group for i, group in enumerate(A)}

>>> {'group1': [12, 13, 15], 'group2': [13, 16, 18], 'group3': [15, 15, 17]}

Upvotes: 1

Related Questions