Home > OS >  How to use variable's value instead of it's identifier?
How to use variable's value instead of it's identifier?

Time:12-03

I'm making a program to output the scientific name of specific fruits from input. This is my source:

import time;

fruits={
    "apple":"Malus domestica",
    "banana":"Musa acuminata",
    "orange":"Citrus sinensis",
    "lychee":"Litchi chinensis",
};

fruit=input("Enter a fruit(either an apple, banana, orange, or lychee):");

if fruit in fruits:
    print("Your fruit's scientific name is " fruits.fruit "\n");
else:
    print("Sorry, the fruit you entered was not in the database");

But when I enter "orange" as my input into the console, the compiler throws an error message:

Traceback (most recent call last):
  File "<string>", line 13, in <module>
AttributeError: 'dict' object has no attribute 'fruit'
> 

Is there any way to use the value of "fruit" rather than use it as a dict element?

CodePudding user response:

Use []:

print(f"Your fruit's scientific name is {fruits[fruit]}\n")

CodePudding user response:

You should update your code from this:

if fruit in fruits:
    print("Your fruit's scientific name is " fruits.fruit "\n");

to this:

if fruit in fruits:
    print("Your fruit's scientific name is " fruits[fruit] "\n");
  • Related