I want to return the value only when providing the key to a function. Using below, if the key is provided, the linked value should be returned. If the key does not exist, then return 'Fruit Not Found'.
Steps:
create empty list to append values
iterate key, value from dict
if given parameter is a key, append to list. else return not found
return list value
code:
fruits = {"Apple": 8, "Orange": 7, "Lemon": 9, "Lime": 5, "Banana": 20}
def fruit_price(x):
price = []
for k,v in fruits.items():
if x in k:
price.append(x)
else:
print('Fruit Not Found')
return price
fruit_price('Lemon')
Exp output:
9
You don't need to create a loop. Square brackets are used to get the value from the dictionary. You can use try-except constructions. If the KeyError occurs in the 'try' block that there is no value for the key, then the code from the 'except' block will be executed
fruits = {"Apple": 8, "Orange": 7, "Lemon": 9, "Lime": 5, "Banana": 20}
def fruit_price(fruit: str):
try:
return fruits[fruit]
except KeyError:
return fruit + ' is not found'
fruit_price('Lemon')
fruit_price('Melon')
Output:
9
Melon is not found
Actually you can just use get()
method, if the value for the key doesn't exist, it returns 'None' or whatever you want
fruit1 = 'Lemon'
fruit2 = 'Melon'
# The first argument is a "key"
# The second argument "default" is what the method returns if the value for the key doesn't exist
# It is not necessary to pass the value of the second argument
# Because, by default, the second argument is None
fruits.get(fruit1, fruit1 + ' is not found')
fruits.get(fruit2, fruit2 + ' is not found')
fruits.get(fruit2)
Output:
9
Melon is not found
None