❓ Help DICTIONARY PYTHON CODE

Certainly! Here's a Python program that demonstrates how to display a message when a key is not found in a dictionary:

Python:
def display_message(dictionary, key):
    if key in dictionary:
        print(f"The value of {key} is {dictionary[key]}")
    else:
        print(f"The key {key} was not found in the dictionary.")

# Example usage
my_dictionary = {"apple": "a sweet fruit", "banana": "a yellow fruit", "orange": "a citrus fruit"}

display_message(my_dictionary, "apple")  # Output: The value of apple is a sweet fruit
display_message(my_dictionary, "pear")   # Output: The key pear was not found in the dictionary.

In this program, the display_message function takes two parameters: dictionary and key. It checks if the key exists in the dictionary using the in operator. If the key is found, it prints the corresponding value. Otherwise, it prints a message indicating that the key was not found in the dictionary.
 

About this Thread

  • 1
    Replies
  • 352
    Views
  • 1
    Participants
Last reply from:
Unknown user

Online now

Members online
971
Guests online
6,447
Total visitors
7,418

Forum statistics

Threads
2,348,881
Posts
29,359,303
Members
1,092,747
Latest member
Gatongka
Back
Top