6

I'm using this code, straight from the scikit-learn page. It creates a dictionary:

symbol_dict = {
    'TOT': 'Total',
    'XOM': 'Exxon',
    'CVX': 'Chevron',}
symbols, names = np.array(symbol_dict.items()).T

But I get an error:

TypeError: iteration over a 0-d array

This code is straight from the example code, so I have no idea what's going wrong.

5
  • Can you post the full traceback? Commented Jan 18, 2014 at 0:46
  • Your code works perfectly when I try it. The problem seems to be coming from something you haven't shown. The traceback would make debugging this much easier. Commented Jan 18, 2014 at 0:52
  • 8
    Are you on Python 3? On Python 3, items returns a dict view, which NumPy doesn't understand. Use np.array(list(symbol_dict.items())).T to turn the view into a list of tuples, which NumPy will recognize properly. Commented Jan 18, 2014 at 1:03
  • Thanks user2357112 That fixes things. Commented Jan 18, 2014 at 1:12
  • 2
    user2357112, This fixed it for me too. Why not post this as the answer? Commented Jul 3, 2016 at 13:47

1 Answer 1

2

As user2357112 said, in Python 3 dict.items() returns a dictionary view object rather than a list of key-value pairs (the difference is explained here). Wrapping it in list() creates a list which is something NumPy can turn into an array:

np.array(list(symbol_dict.items()))
Sign up to request clarification or add additional context in comments.

Comments

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.