Roman
Roman

Reputation: 3241

pythonic way of changing old names by new names

I have to replace the oldnames as the newnames inside the program as follows:

oldnames = ['apple','banana','sheep']

for oldname in oldnames:
    if oldname == 'apple':
        newname = 'monkey'

    if oldname == 'banana':
        newname = 'monkey'

    if oldname == 'sheep':
        newname = 'lion'

My program is doing well, but wondering what is the best pythonic way of doing it?

Upvotes: 0

Views: 72

Answers (3)

Okto
Okto

Reputation: 96

even more pythonic

oldnames = ["apple", "banana", "sheep"]
translate = { "apple": "monkey", "banana": "monkey", "sheep": "lion" }

newnames = map(translate.get, oldnames)

Upvotes: 0

Joaquin Sargiotto
Joaquin Sargiotto

Reputation: 1746

Also using dictionaries, but I think this is simpler:

# Original values
oldnames = ["apple", "banana", "sheep"]

# Conversion table
translate = {
    "apple": "monkey",
    "banana": "monkey",
    "sheep": "lion",
}

# For each oldname, get the translated value
newnames = [translate.get(x) for x in oldnames]

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117906

You can use a dictionary to handle the replacements, for example

>>> replacements = {'apple':'monkey',
                    'banana':'monkey',
                    'sheep':'lion'}
>>> s = "The apple and the banana saw a sheep"
>>> ' '.join(replacements.get(word,word) for word in s.split())
'The monkey and the monkey saw a lion'

Upvotes: 6

Related Questions