Home > Software engineering >  Matching user input (variable) with list item and printing item
Matching user input (variable) with list item and printing item

Time:12-02

I apologize for the incomprehensible title (I'm new to python). Couldn't write a better one.

Anyway, I have a list, colors = ['Red', 'Green', 'Blue', 'Yellow', 'Purple', 'Orange', 'White'].

Then I assign variables to these items as r = Red, b = Blue and so on.

Now, when I ask the user to select an item using its first letter such as r, I want to print Red. Similarly if user selects g, then print Green and so on.

I want to achieve this without using if statements. I know this might be very simple but I am a beginner and I tried my level best to search all of the internet to this solution but couldn't find. If possible, please use f-strings.

Thank you in advance!

CodePudding user response:

Keep the colors in a dictionary instead of a list.

colors = {
    'r': 'Red',
    'b': 'Blue',
    ...
}

letter = input('Choose a color letter: ')
print(colors[letter])

CodePudding user response:

You can create a map from first letter to full color name

def get_color(letter):
    colors = ['Red', 'Green', 'Blue', 'Yellow', 'Purple', 'Orange', 'White']
    color_map = {s[0].lower(): s for s in colors}
    return color_map.get(letter, '')

>>> get_color('r')
'Red'
>>> get_color('b')
'Blue'
>>> get_color('x')  # doesn't exist
''

Note that this will not handle cases with duplicate first letter (e.g. "Blue" and "Black").

  • Related