Pundun
Pundun

Reputation: 33

mapping dictionary value to list and return original value if key doesn't exist

I have a list seems like this :

a = ['jokowi','jokowidodo','ir h jokowidodo','teungku']

and a dictionary like this

{'jokowi': 'jokowi', 'jokowidodo': 'jokowi', 'ir h jokowidodo': 'jokowi'}

and make a mapping using this code:

list(map(data_dict.get,listakoh))

and then it returns:

['jokowi', 'jokowi', 'jokowi', None]

the question is how can I replace None in the result with the original value of my previous list, so None in the result must be 'teungku'

Upvotes: 0

Views: 716

Answers (3)

Austin
Austin

Reputation: 26037

You can use a second argument to get as a default value:

list(map(lambda x: data_dict.get(x, x), a))

Upvotes: 2

AfiJaabb
AfiJaabb

Reputation: 306

You can easily compare the mapped list with the original list and replace the None values with those from the actual list.

>>> new_list = list(map(data_dict.get,listakoh))
>>> for index, element in enumerate(new_list):
    if element == None:
        new_list[index]=a[index]

>>> print(new_list)
['jokowi', 'jokowi', 'jokowi', 'teungku']

Upvotes: 0

alec_djinn
alec_djinn

Reputation: 10819

You can simply define your own function and map that.

a = ['jokowi','jokowidodo','ir h jokowidodo','teungku']
d = {'jokowi': 'jokowi', 'jokowidodo': 'jokowi', 'ir h jokowidodo': 'jokowi'}

def f(k):
    global d
    try:
        return d[k]
    except KeyError:
        return k

r = list(map(f, a))
print(r)

['jokowi', 'jokowi', 'jokowi', 'teungku']

Upvotes: 0

Related Questions