Home > Enterprise >  How to replace part of the values in the list using the values from the dictionary?
How to replace part of the values in the list using the values from the dictionary?

Time:09-30

The following method can only replace one value:

my_list = ['apple', 'pear', 'grape', 'banana', 'kiwi', 'plum']
my_list = list(map(lambda x: x.replace('apple','strawberry'), my_list))
print(my_list)

['strawberry', 'pear', 'grape', 'banana', 'kiwi', 'plum']

I wanted to try adding a dictionary instead of a pair of values ("old","new"):

my_list = list(map(lambda x: x.replace({'apple':'strawberry', 'banana':'raspberry'}), my_list))

But an error message appears: "replace() takes at least 2 arguments (1 given)"

CodePudding user response:

You can do like this,

d = {"apple": "strawberry", "banana": "raspberry"}
out = list(map(lambda x: d.get(x, x), my_list))

# Output
# ['strawberry', 'pear', 'grape', 'raspberry', 'kiwi', 'plum']

CodePudding user response:

Since replace is returning a string you can call it again, try this:

my_list = ['apple', 'pear', 'grape', 'banana', 'kiwi', 'plum']
my_list = list(map(lambda x: x.replace('apple','strawberry').replace("banana", "raspberry"), my_list))
print(my_list)

If you have a lot of key:value-pairs you might want to use functools.reduce

from functools import reduce
replacements = ('apple','strawberry'), ("banana", "raspberry")
my_list = [reduce(lambda a, kv: a.replace(*kv), replacements, x) for x in my_list]
print(my_list)
  • Related