How to create a dictionary of arrays to strings in Python?

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 answers

  • answered 2017-11-14 23:49 Moses Koledoye

    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']
    

  • answered 2017-11-15 00:03 joshuakcockrell

    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']
    

  • answered 2017-11-15 00:37 B. M.

    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]
    

  • answered 2017-11-15 01:26 Arnav Poddar

    Even though this might not be what you wanted, you could just make a bunch of variables equal to arrays get added to the list.