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

Raja Sattiraju
  • 1,262
  • 1
  • 20
  • 42

2 Answers2

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]])}
tobias_k
  • 81,265
  • 12
  • 120
  • 179
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]])]
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
  • This method is almost twice as fast than using a dictionaray. Thank you so much – Raja Sattiraju Jul 15 '16 at 10:20
  • you are welcome! Certainly because I turned around `zip` (but you can use `izip` from `itertools`) – Colonel Beauvel Jul 15 '16 at 10:26
  • Does `b.keys()` guarantee that the keys come out in sorted (or any specific) order? – tobias_k Jul 15 '16 at 11:18
  • Answer is there: http://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order – Colonel Beauvel Jul 15 '16 at 11:20
  • 1
    @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). – tobias_k Jul 15 '16 at 11:30