2

I have a numpy array

[['5.1', '3.5', '1.4', '0.2', 'Setosa'],
 ['4.9', '3.0', '1.4', '0.2', 'Versicolor']]

How to convert it to a dictionary such that

{['5.1', '3.5', '1.4', '0.2']:'Setosa', ['4.9', '3.0', '1.4', '0.2']:'Versicolor'}
4
  • I'm assuming you ment 'Setosa' and 'Versicolor' instead of 'Iris-setosa' in that example output, right? Commented Apr 6, 2014 at 11:22
  • 2
    this isn't really specific to numpy is it? Commented Apr 6, 2014 at 11:55
  • 1
    @TooTone Indeed. The solution I proposed works fine on regular nested lists as well. Commented Apr 6, 2014 at 12:43
  • @Joost I know: I tried it :) Commented Apr 6, 2014 at 12:47

1 Answer 1

7

The dictionary you're currently specifying is invalid, since the keys of your dictionaries cannot be list objects. However, you could change them to tuples. As tuples are immutable, they can be used as keys.

A dictionary comprehension that converts the sample case you have provided might look like this:

a = numpy.array([['5.1', '3.5', '1.4', '0.2', 'Setosa'],
                 ['4.9', '3.0', '1.4', '0.2', 'Versicolor']])
b = {tuple(x[:-1]) : x[-1] for x in a}

It creates a tuple from the first n-1 elements of each list, and then assigns the last element as the value. The resulting dictionary looks like this:

{('5.1', '3.5', '1.4', '0.2'): 'Setosa', ('4.9', '3.0', '1.4', '0.2'): 'Versicolor'}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.