return a list or array that contains values based on dictionary keys without using for loop

Question:

I have a dictionary {'A':1,'B':2,'C':3}

i want to map a list ['A','B','A','A','B] to dictionary values without using for loop or unnecessary if statements the output should be [1,2,1,1,2] in array or list from.

I tried to do this using np.vectorize and map but it is a for loop. I need to do this without using any loops or unnecessary if statements to get the required result mentioned above.

Asked By: Syed Muhammad Zain

||

Answers:

You can use itemgetter

from operator import itemgetter

d = {'A': 1, 'B': 2, 'C': 3}
lst = ['A', 'B', 'A', 'A', 'B']
lst = itemgetter(*lst)(d)
print(lst) # (1, 2, 1, 1, 2)
Answered By: Guy

Here’s a solution without for loops or if statements, as per your specification.

d = {'A':1,'B':2,'C':3}
l = ['A','B','A','A','B','z']

def replace_in_list(mapping, list_iterator):
    try:
        val = mapping[next(list_iterator)]
    except KeyError:
        val = None
    except StopIteration:
        return []
    return [val] + replace_in_list(mapping, list_iterator)

result = replace_in_list(d, iter(l))
print(result)  # [1, 2, 1, 1, 2, None]
Answered By: Fractalism

This could be done using list or map with dictionary ‘get’

d = {'A':1,'B':2,'C':3}
l = ['A','B','A','A','B']
result = list(map(d.get, l))
Answered By: kincaid

Another possible solution, based on numpy:

(np.sum((np.array(l) == np.array(list(d.keys()))[:,None]) *
        np.array(list(d.values()))[:,None], axis=0))

Output:

array([1, 2, 1, 1, 2])
Answered By: PaulS
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.