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

Time:01-29

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.

CodePudding user response:

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)

CodePudding user response:

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]

CodePudding user response:

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))

CodePudding user response:

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])
  • Related