How to print specific value in a dictionary without the brackets based on user choice

Question:

I am learning python and I have the following scenario: Create a data structure that associates two values. Then retrieve the specific data without using an if/else statement. This is what I came up with.

def menu():
 print("1. fruit 1")
 print("2. fruit 2")
 print("3. fruit 3")

fruits = {
  1: ["Fruit 1", "Message", "Healthy"],
  2: ["Fruit 2", "Message", "Unhealthy"],
  3: ["Fruit 3", "Message", "Healthy"]
 }
 
 menu()
 option = int(input("Choose your fruit: ")
 print(fruits.get(option))

This works but it prints out the brackets and quotation marks. How do I make it prettier? I’ve seen other examples but it usually only deals with a simple one line dictionary without user input. Any help is appreciated.

Asked By: user2816227

||

Answers:

You could use:

print(', '.join(fruits.get(option, ['Invalid fruit'])))

This will give a comma-separated list of the values, and an error message if the fruit doesn’t exist. For example in a loop:

fruits = {
  1: ["Fruit 1", "Message", "Healthy"],
  2: ["Fruit 2", "Message", "Unhealthy"],
  3: ["Fruit 3", "Message", "Healthy"]
 }

for option in range(5):
    print(', '.join(fruits.get(option, ['Invalid fruit'])))

Output:

Invalid fruit
Fruit 1, Message, Healthy
Fruit 2, Message, Unhealthy
Fruit 3, Message, Healthy
Invalid fruit
Answered By: Nick

Use format:

option = int(input("Choose your fruit: "))
fruit = fruits.get(option)
if fruit is not None:
    print(f"{fruit[0]}, {fruit[1]}, {fruit[2]}")
Answered By: Shimizu Hino
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.