简体   繁体   中英

Can I create a numpy array of dictionary values from an array of dictionary keys?

Say I have a dictionary:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Given a numpy array** of keys, eg ['a' 'c' 'e'] , is there an easy way to create a numpy array of the corresponding values, eg [1 3 5] ?

** for reasons of the context I'm using this in, I'd prefer to input/output numpy arrays. Something similar can obviously be done with lists:

keys = ['a', 'c', 'e']
values = []

for k in keys:
    values.append(d[k])

print(values)
[1, 3, 5]

But I am wondering if there is a built-in way to do something like this in numpy.

You could do this with a structured array and np.in1d .

import numpy as np

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

# Create structured array (modify formats, names as necessary):
names = ['key', 'data']  
formats = ['U10', 'i4']                                                                        
dtype = dict(names = names, formats = formats)

arr = np.array(list(d.items()), dtype=dtype)

# >>> arr
# array([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)],
#       dtype=[('key', '<U10'), ('data', '<i4')])

# use np.in1d to get your keys:

keys = ['a', 'c', 'e']

values = arr[np.in1d(arr['key'], keys)]['data']                                                

# >>> values
# array([1, 3, 5], dtype=int32)

If you just require to have numpy arrays as input and output but don't insist on using a numpy function to handle them, you can use numpy.array() on the result of a list comprehension:

import numpy as np

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
keys = np.array(['a', 'c', 'e'])
values = np.array([d[k] for k in keys])

print(values)

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