1

I have two dicts

a = {0:[1,2,3,4], 1:[5,6,7,8],...}
b = {0:[4,3,2,1], 1:[8,7,6,5],...}

I would like to create an np.array c for each key-value pair such as follows

c1 = array([[1,4],[2,3],[3,2],[4,1]])
c2 = array([[5,8],[6,7],[7,6],[8,5]])

How can I do this? Is it possible to store np.array in a python dict so that I can create a single dict c instead of multiple arrays

2 Answers 2

3

Yes, you can put np.array into a Python dictionary. Just use a dict comprehension and zip the lists from a and b together.

>>> a = {0:[1,2,3,4], 1:[5,6,7,8]}
>>> b = {0:[4,3,2,1], 1:[8,7,6,5]}
>>> c = {i: np.array(list(zip(a[i], b[i]))) for i in set(a) & set(b)}
>>> c
{0: array([[1, 4], [2, 3], [3, 2], [4, 1]]),
 1: array([[5, 8], [6, 7], [7, 6], [8, 5]])}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Thank you so much. Works elegantly
2

You can also use column_stack with a list comprehension:

import numpy as np

[np.column_stack((a[k], b[k])) for k in b.keys()]

Out[30]:
[array([[1, 4],
        [2, 3],
        [3, 2],
        [4, 1]]), array([[5, 8],
        [6, 7],
        [7, 6],
        [8, 5]])]

5 Comments

This method is almost twice as fast than using a dictionaray. Thank you so much
you are welcome! Certainly because I turned around zip (but you can use izip from itertools)
Does b.keys() guarantee that the keys come out in sorted (or any specific) order?
@ColonelBeauvel That was not the question, but whether it's possible that the resulting array ends up as [c2, c1] instead of [c1, c2]. Using a dict with 100 keys being random numbers from 1 to 1000, keys() seems to return the keys in random order (Python 2 and 3).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.