-1

I have a dictionary, each key of dictionary has a list of list (nested list) as its value. What I want is imagine we have:

x = {1: [[1, 2], [3, 5]], 2: [[2, 1], [2, 6]], 3: [[1, 5], [5, 4]]}

My question is how can I access each element of the dictionary and concatenate those with same index: for example first list from all keys:

[1,2] from first keye + 
[2,1] from second and 
[1,5] from third one 

How can I do this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    What do you mean by "same index"? Can you provide an example of the expected output? – Luca Jan 13 '22 at 12:34
  • Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) i.e. `zip(*x.values()`... – Tomerikoo Jan 13 '22 at 18:05
  • In the title you said something about sum but never explained it in the question... – Tomerikoo Jan 13 '22 at 18:08

4 Answers4

0

You can access your nested list easily when you're iterating through your dictionary and append it to a new list and the you apply the sum function.

Code:

x={1: [[1,2],[3,5]] , 2:[[2,1],[2,6]], 3:[[1,5],[5,4]]}
ans=[]
for key in x:
    ans += x[key][0]
print(sum(ans))

Output:

12

Thekingis007
  • 627
  • 2
  • 16
0

Assuming you want a list of the first elements, you can do:

>>> x={1: [[1,2],[3,5]] , 2:[[2,1],[2,6]], 3:[[1,5],[5,4]]}
>>> y = [a[0] for a in x.values()]
>>> y
[[1, 2], [2, 1], [1, 5]]

If you want the second element, you can use a[1], etc.

VBB
  • 1,305
  • 7
  • 17
0

The output you expect is not entirely clear (do you want to sum? concatenate?), but what seems clear is that you want to handle the values as matrices.

You can use numpy for that:

summing the values
import numpy as np

sum(map(np.array, x.values())).tolist()

output:

[[4, 8], [10, 15]]        # [[1+2+1, 2+1+5], [3+2+5, 5+6+4]]
concatenating the matrices (horizontally)
import numpy as np

np.hstack(list(map(np.array, x.values()))).tolist()

output:

[[1, 2, 2, 1, 1, 5], [3, 5, 2, 6, 5, 4]]
mozway
  • 194,879
  • 13
  • 39
  • 75
0

As explained in How to iterate through two lists in parallel?, zip does exactly that: iterates over a few iterables at the same time and generates tuples of matching-index items from all iterables.

In your case, the iterables are the values of the dict. So just unpack the values to zip:

x = {1: [[1, 2], [3, 5]], 2: [[2, 1], [2, 6]], 3: [[1, 5], [5, 4]]}

for y in zip(*x.values()):
    print(y)

Gives:

([1, 2], [2, 1], [1, 5])
([3, 5], [2, 6], [5, 4])
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61