0

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)
1
  • Try OrderedDict: docs.python.org/2/library/collections.html Commented May 15, 2017 at 12:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The gains here are marginal, but are sure to widen with the size of the dataset

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.