anplaceb
anplaceb

Reputation: 33

Iterate through a dictionary with matrix

I have this 2 matrix:

x = np.matrix("1 2 3; 4 5 6")
y = np.matrix("7 8 9; 10 11 12")

...and I put them in a dictionary

d = {"a" : x, "b": y}

Now I want to extract the values of the matrix that have the same position together, like this: 1,7...2,8...3,9... and so on until 6,12 (expected output).

I only managed to do it manually, like this:

   [value[0,0] for value in d.values()]

I´m trying to build a loop for this, but didn´t manage to do it.

Can someone give me a hand please?

Upvotes: 1

Views: 311

Answers (1)

Sam Chats
Sam Chats

Reputation: 2321

You can do something like:

values = zip(*d.values()) # gives [([1, 2, 3], [7, 8, 9]), ([4, 5, 6], [10, 11, 12])]
pairs = []
for value in values:
    pairs.extend(zip(*value)) #adds (1, 7), (2, 8), ... to pairs list

for pair in pairs:
    print(pair)

Output:

(1, 7)
(2, 8)
(3, 9)
(4, 10)
(5, 11)
(6, 12)

Upvotes: 4

Related Questions