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

Time:10-09

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?

CodePudding user response:

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']

CodePudding user response:

The only way to use lambda I can think of is using map and dict.get:

l = ['yellow', 'red', 'green',  'blue']
d = {'green': 'go', 'yellow': 'attention', 'red': 'stay'}
out = map(lambda x: d.get(x, x), l)
print(list(out))

Result

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