简体   繁体   中英

How to make a numpy array with a dictionary's values?

If I have a dictionary that looks like this:

sam = {1:np.array([1,2,3,4]), 2:np.array([2,4,6,8]) }

How can I make a numpy array with the dictionary values like this?

arr = ([[1,2,3,4], 
        [2,4,6,8]])

I thought np.fromiter(sam.values(), dtype=np.int16) might work, but it doesn't work probably because of its dtype.

Are the any functions to do this, instead of using for or any loops?

You could stack the values of your dictionary like this:

arr = np.stack(sam.values())

>>> arr
array([[1, 2, 3, 4],
       [2, 4, 6, 8]])

Dictionaries aren't considered ordered unless you are using Python 3.7+. So this is messy, but possible. The idea is to sort dict.items by key to give a list of tuples, then extract values.

from operator import itemgetter as iget

res = np.array(list(map(iget(1), sorted(sam.items(), key=iget(0)))))

array([[1, 2, 3, 4],
       [2, 4, 6, 8]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM