pythonlistdictionarylambdamatching

How to replace elements in python list by values from dictionary if list-element = dict-key?


input:

[yellow, red, green,  blue]

{green:go, yellow:attention, red:stay}

how to make new list:

[attention, stay, go, blue]

are there way to make it with lambda?


Solution

  • Use dict.get inside a list comprehension:

    lst = ["yellow", "red", "green",  "blue"]
    dic = {"green":"go", "yellow":"attention", "red":"stay"}
    res = [dic.get(e, e) for e in lst]
    print(res)
    

    Output

    ['attention', 'stay', 'go', 'blue']