galliwuzz
galliwuzz

Reputation: 369

Convert dictionary values into array sorted by another array

I have a dictionary

mydict = {'jon': 12, 'alex': 17, 'jane': 13}

and I want to create a np.array which contains the values 12, 17, 13, but sorted by another array

sortby = np.array(['jon', 'jane', 'alex'])

which should yield the output as

sorted_array = np.array([12, 13, 17])

Any approaches that are more efficient than looping through the sortby array like below?

sorted_array = []
for vals in sortby:
     sorted_array.append(mydict[vals])

return np.array(sorted_array)

Upvotes: 0

Views: 86

Answers (1)

Rahul K P
Rahul K P

Reputation: 16091

Use list comprehension,

In [100]: np.array([mydict[i] for i in sortby])
Out[100]: array([12, 13, 17])

Edit:

Execution timings, To make clear for mohammad and Moses Discussions

In [119]: def test_loop():
    sorted_array = []
    for vals in sortby:
        sorted_array.append(mydict[vals])
    return np.array(sorted_array)
   .....: 

In [120]: def test_list_compres():
    return np.array([mydict[i] for i in sortby])
   .....: 

In [121]: %timeit test_list_compres
10000000 loops, best of 3: 20 ns per loop

In [122]: %timeit test_loop
10000000 loops, best of 3: 21.3 ns per loop

In [123]: %timeit test_list_compres
10000000 loops, best of 3: 20.1 ns per loop

In [124]: %timeit test_loop
10000000 loops, best of 3: 21.9 ns per loop

It's a marginal difference but it will make a significant change with huge entries.

Upvotes: 2

Related Questions