Using Python Dictionaries to Solve Real-World Problems: A Menu-Driven Program Example

Using Python Dictionaries to Solve Real-World Problems: A Menu-Driven Program Example

Welcome back to another exciting edition of Python Programming!

In this edition, we will provide a quick brush-up on dictionaries in Python and demonstrate their practical application through a problem statement.

If you're new to dictionaries or need a refresher, this article will help you recall the key concepts and showcase how dictionaries can be used to solve real-world problems.

In the world of programming, beginners often focus on learning the syntax of programming languages and practicing standard programs. However, without proper guidance, they may struggle to understand where and how to apply the concepts they've learned to solve real-world problems.

In this edition, we will address this challenge by demonstrating the practical usage of dictionaries in Python. Dictionaries are a powerful data structure that can be applied to various real-world problems. They play a crucial role in Python programming, allowing us to store and retrieve data efficiently.

How do dictionaries relate to solving real-world problems?

To understand the relevance of dictionaries in solving real-world problems, let's consider a specific scenario.

Imagine you are building a language-learning application that needs to store a large collection of words and their corresponding meanings

Here's where dictionaries come into play. You can use a dictionary to associate each word with its corresponding meanings

In this case, the word serves as the key, and the meaning serves as the associated value. By leveraging dictionaries, you can easily retrieve the meaning of a word, add new entries, update existing ones, or search for specific words—all with efficient access and retrieval.

Problem statement:

Create a dictionary of elements having words and their corresponding meanings. Develop a menu driven program that offers user with the following options

1.Add a new word to the dictionary

2.Display the contents of dictionary

3.Delete a word from the dictionary

4.Search for the meaning of word

5.Modify the meaning of word

6.Quit

Program should continue to work until User wishes to quit.

We have discussed regarding Dictionary data structure in detail in one of the editions. If you are new to dictionaries Kindly visit Python Dictionaries

However, dictionary concepts are covered in this article too in short for quick brush up.

What is dictionary?

It is one of the data structures supported in Python Programming, that stores elements in a Key:Value pairs. It means that there is an association with key and its corresponding value.

For instance, Roll number of student is associated with his/her name.

Hence, Roll number acts as key and name will be the corresponding value.

One of the points to be observed here is that Roll number is unique, because no two students can have the same Roll number. But multiple students name could be same.

Therefore, Key of the dictionary plays an important role in identifying the element.

How to create dictionary?

# create an empty dictionary
students = {}
# dictionary with multiple elements
students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}
# print entire dictionary
print(students)        

Output

{1: 'Neha', 2: 'Nidhi', 3: 'Sanath'}        

How to extract individual elements from the dictionary?

Note: An element refers to Key:Value pair

students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}

# Access individual elements by key
print(students[1])  # Output: Neha
print(students[2])  # Output: Nidhi
print(students[3])  # Output: Sanath        

Here is the output

#Output
Neha
Nidhi
Sanath        

We can use items method and Loop to print all the key:value pairs

students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}

# Access individual elements (key-value pairs)
for element in students.items():
    key, value = element
    print(key, value)
#Output
1 Neha
2 Nidhi
3 Sanath        

How to delete elements from dictionary?

Using del statement

students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}

# Delete an element by key using del
del students[1]

# Print the modified dictionary
print(students)        

Output

{2: 'Nidhi', 3: 'Sanath'}        

Let's have a look at membership operators quickly, because we are going to use them

"in" and "not in" Operator

in operator with dictionaries: It checks if a key is present in a dictionary and returns True if the key is found, and False otherwise.
students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}
print(1 in students)  # Output: True
print(4 in students)  # Output: False        
not in operator with dictionaries: It checks if a key is not present in a dictionary and returns True if the key is not found, and False otherwise.
students = {1: "Neha", 2: "Nidhi", 3: "Sanath"}
print(4 not in students)  # Output: True
print(2 not in students)  # Output: False        

With this knowledge we can easily solve the problem in hand. So first analyze the problem step by step.

Create a dictionary of elements having words and their corresponding meanings. Develop a menu driven program that offers user with the following options

1.Add a new word to the dictionary

2.Display the contents of dictionary

3.Delete a word from the dictionary

4.Search for the meaning of word

5.Modify the meaning of word

6.Quit

Program should continue to work until User wishes to quit.

  1. We need a dictionary to keep words and their corresponding meaning.
  2. Provide a menu of options to the user such as, adding a new word in the dictionary of words, deleting a word, modifying the meaning of a word, searching for the meaning of a word, to see all the words along with meanings
  3. prompt for selecting user's choice
  4. For every option appropriate code with validations. For instance, when the user wants to delete a new word, our code should check whether such word exists in dictionary and provide suitable message. Because word which doesn't exist can't be deleted. Here, we make use of membership operators (in, not in) appropriately.
  5. User must be provided with a menu again once he completes his previous action. That means the entire process should be repeated until user wants to quit. Hence, we require loop concepts. You can read more about loops here Loop Statements in Python

Let's implement it.

d = {'a':'attitude','d':'dignity','m':'moral'}
#Display Menu              
choice1 = 'y'
while(choice1 == 'y'):
  print("1. Add a New Entry (Word and Meaning")
  print("2. Display the contents of dictionary")
  print("3. Delete a word from the dictionary")
  print("4. Search for the meaning of word")
  print("5. Modify the meaning of word")
  print("6. Quit")
    
  choice = int(input("Enter Your Choice: "))

  if(choice == 1):
    key = input("Enter the word: ")
    value = input("Enter the Meaning: ")
    if(key not in d):
      d[key] = value
    else:
      print("This word already exist ", d)

  if(choice == 2):
    for element in d.items():
      key, value = element
      print(key, value)

  if(choice == 3):
    word = input("Which word you would like to delete? ")
    if(word in d):
      del(d[word])
      print("Updated Dictionary: ",d)
    else:
      print("No such word is present in the dictionary ",d)       
  
  if(choice == 4):
      meaning = input("Which word's meaning you would like to know? ")
      if(meaning in d):
        print(d[meaning])
      else:
        print("No such word is present in the dictionary ", d)
  
  if(choice == 5):
      word = input("Which word's meaning you would like to change? ")
      if(word in d):
        new = input("Enter the new meaning: ")
        d[word] = new
        print("Updated Dictionary: ",d)
      else:
        print("No such word is present in the dictionary ",d) 
    
   if(choice == 6):
      break
    choice1=input(("Do you wish to go back to the main menu? (y/n) "))
    
  print("Thank You! Have Good Time")         

Yes, We did it!!

This is just a taste of what dictionaries can do, but I hope it's left you hungry for more. Share your thoughts and ideas in the comments—I'd love to hear them!

Now, it's time to gear up for our next edition, where we'll explore another exhilarating topic in Python programming.

Stay curious, keep coding, and let the adventures continue!

Happy Coding!!

Mahima K. Manish

React.js | Vue 3 I Nuxt 3 I Tailwind CSS | Material UI

1y

#cfbr

Like
Reply

To view or add a comment, sign in

More articles by Swarooprani Manoor

Insights from the community

Others also viewed

Explore topics