Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 653
Константин Прудников Avatar asked Dec 31 '25 16:12

Константин Прудников


1 Answers

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']
like image 101
Dani Mesejo Avatar answered Jan 02 '26 06:01

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!