0

I'm trying to create a dictionary that maps a specific array like [1,1,0,0] to a string 'Car' but the dictionary does not accept arrays or lists

a={(1,1,0,0):'Car',
(0,0,0,1):'Pedestrian',    
(1,0,0,0):'Traffic Light'}

b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])

Both codes are free of errors but obviously they don't match. Here is my idea:

b.map(a)

Out[3]=['Car','Traffic Light','Pedestrian']

Thanks in advance.

4
  • A dict key must be an immutable type; that's why tuples work, but lists don't. Commented Nov 14, 2017 at 23:49
  • Yes, dict objects cannot have list or np.array objects as keys. Perhaps tuple(my_list) as a key? Commented Nov 14, 2017 at 23:50
  • It looks like your dict + array solution will work, once you use map as defined. Where are you stuck? Commented Nov 14, 2017 at 23:50
  • Also, np.ndarray objects don't have a .map method... Commented Nov 14, 2017 at 23:54

3 Answers 3

1

A simple list comprehension will do, converting each inner array to a tuple before passing it to the dict for lookup:

>>> out = [a[tuple(x)] for x in b]
>>> out
['Car', 'Traffic Light', 'Pedestrian']
Sign up to request clarification or add additional context in comments.

Comments

0

You can grab the string using a tuple as a key. The reason you can't use a list as a key is because lists can be modified, and you wouldn't other spots in your code modifying your dictionary keys.

>>> a[[1,1,0,0]] # Won't work because it's not a tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> a[(1,1,0,0)] # Works
'Car'

If you want to use the list as a key, then you can convert it

>>> a[tuple([1,1,0,0])]
'Car'

If you have a list of arrays (like in your example) then you can grab all their matching strings like this

>>> b=np.array([[1,1,0,0],[1,0,0,0],[0,0,0,1]])
>>> [a[tuple(eachList)] for eachList in b]
['Car','Traffic Light','Pedestrian']

Comments

0

If you are looking after efficiency if b is a big array, transform it in hashable keys :

B=(b<<np.arange(4)).sum(1)
# array([3, 1, 8], dtype=int32)

Then define dict as :

A={1: 'Traffic Light', 3: 'Car', 8: 'Pedestrian'}

The mapping now can be:

[A[key] for key in B]

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.