1

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?

1 Answer 1

4

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)
5
  • Note that the dictionary order is not guaranteed, so the output could end up being (7, 1) (8, 2) (9, 3) (10, 4) (11, 5) (12, 6). Jun 28, 2017 at 18:15
  • @StevenRumbalski yes, then we can simply use values = zip(x, y) instead of values = zip(*d.values()).
    – Sam Chats
    Jun 28, 2017 at 18:16
  • 1
    Not that this is any better, but pairs = zip(*[v.flat for v in d.values()]) Jun 28, 2017 at 18:42
  • 1
    Thanks, but I don't get the same result. Maybe it's because I'm using python 3(?). I tried to write the first line this way: values = list(zip(*d.values())) but I get this result: [(matrix([[1, 2, 3]]), matrix([[7, 8, 9]])), (matrix([[4, 5, 6]]), matrix([[10, 11, 12]]))] which is also the result I get if I run the whole code. Meanwhile I came up with an alternative solution: for x in range(0,2): for y in range(0,3): print([value[x, y] for value in d.values()]) but it would still interest me how to use the zip() function.
    – anplaceb
    Jun 29, 2017 at 16:14
  • @anplaceb Oh that's because you're using numpy arrays and I used Python lists. My code is Python3, so no compatibility issues. And I like your solution. By the way, you can convert to a usual list by doing something like x_list = numpy.array(x).reshape(-1,).tolist(). Then, you can proceed with the code above.
    – Sam Chats
    Jun 29, 2017 at 16:56

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.