Python Dictionary Beginner Project: Python Dictionary Projects to Enhance Your Coding Skills

Python-Dictionary-Beginner-Project
Credit: Canva

Overview

Python Dictionary is a data structure that stores value in key-value pairs. Its data are ordered, and mutable and do not allow duplicate values. Its data elements are indexable only with ‘KEY’. This project involves managing and manipulating data efficiently, a crucial skill for both beginners and advanced programmers.

What’s Next!

Let’s start with the Python Dictionary Beginner Project which includes 5 challenging but beginner-friendly questions to teach you techniques like nested dictionaries, and data manipulations of Python Dictionary. Moreover, this project provides a practical and engaging way to improve your coding abilities.

Table of Contents

Project 1: Phonebook Application

Create a program that simulates a phonebook. The program should allow users to add, remove, and look up contacts by name. Each contact’s name should be a key, and their phone number should be the value.

				
					def menu():
    print('1. Add name: ')
    print('2. Remove name: ')
    print('3. Search name: ')   
    print('4. Display Phonebook: ')
    print('5. Exit ')

def add_name(contacts):
    key = input('Enter user name: ')
    value = input('Enter user number: ')    
    contacts[key] = value
    print(key,'is added successfully.')
    return contacts

def remove_name(contacts):
    name = input('Enter user name: ')
    if name in contacts:
        del contacts[name]
        print(name,'is deleted successfully.')
    else:
        print(name,'does not exist in Phonebook.')

def search_name(contacts):
    name = input('Enter user name to check: ')
    if name in contacts:
        print(f'Here is the detail: {name} {contacts.get(name)}')
    else:
        print(name,'does not exist in Phonebook.')

def show_contacts(contacts):
    print('Here is the Phonebook:',contacts)
    return contacts

contacts = {}

while True:
    menu()
    choice = input('Choose an option: 1. 2. 3. 4. 5. --> ')
    if choice == '1':
        add_name(contacts)
    elif choice == '2':
        remove_name(contacts)
    elif choice == '3':
        search_name(contacts)
    elif choice == '4':
        show_contacts(contacts)
    elif choice == '5':
        print('Exit')
        break
    else:
        print('Invalid Output!')
				
			

Explanation: The program starts by creating multiple functions like adding, removing, and looking up contacts by name respectively and assigning a parameter ‘contacts’.

menu: The function stores some statements/questions, that a user will select to initiate the dictionary operations.

add_name: The function asks the user to enter the key and its value to add to the dictionary in a key-value pair.

remove_name: The function asks for the name from the user, then using the conditional statement, the name is checked if it is in the Dictionary, it is deleted otherwise a message is displayed of ‘does not exist’.

search_name: The function asks for the name from the user, then using the conditional statement, the name is checked if it is in the Dictionary, then the key-value pair is returned otherwise a message is displayed of ‘does not exist’.

show_contacts: The function returns the whole dictionary to display the dictionary.

The Python while loop is used so that a user can perform the operations as long as the user wants. Next, the user selects an option and according to the number, a dictionary operation is performed based on the conditional statement matched with the user’s option.

Project 2: Word Frequency Counter

Write a program that counts the frequency of each word in a given text. The program should store the words as keys and their frequencies as values in a dictionary, then display the word counts.

				
					text = 'I am a boy and boy is a person'
words = text.split()

word_frequency = {}
frequency = 0

for word in words:
    if word in word_frequency:
        word_frequency[word] +=1
    else:
        word_frequency[word] = 1
print(word_frequency)
				
			

Explanation: The program starts with a sequence of characters which is broken down into a list of separated strings by comma, using the split() function.

An empty dictionary is initiated along with a variable frequency of 0 which counts the number of times a word has been repeated into the dictionary.

Now, a for loop is used to access each string one by one, which is later passed to the conditional statement and checked. If it is present in an empty dictionary, then the string count is incremented by 1; otherwise, the string frequency is put to 1. Finally, a dictionary is displayed in key-value pairs, in which the string is a key, whereas the string’s frequency is a value.

Project 3: Student Grades Tracker

Develop a program that tracks student grades for different subjects. The program should allow users to add students and their grades, update grades, and retrieve a student’s grades for a specific subject. Each student’s name should be a key, and their grades (stored in a nested dictionary) should be the values.

				
					student_grades = {}

def add_student(student_name, grades):

    if student_name in student_grades:
        print(f"Student {student_name} already exists.")
    else:
        student_grades[student_name] = grades
        print(f"Added {student_name} with grades: {grades}")

def update_grade(student_name,subject, new_grade):
    if student_name in student_grades:
        if subject in student_grades[student_name]:
            student_grades[student_name][subject] = new_grade
            print(f"Updated {student_name}'s grade for {subject} to {new_grade}.")
        else:
            student_grades[student_name][subject] = new_grade
            print(f"Added {subject} to {student_name}'s grades with a grade of {new_grade}.")

    else:
        print(f"Student {student_name} does not exist.")

def get_student_grade(student_name, subject):
    if student_name in student_grades:
        if subject in student_grades[student_name]:
            print(f"{student_name}'s grade for {subject} is {student_grades[student_name][subject]}.")
        else:
            print(f"{subject} is not found for {student_name}.")
    else:
        print(f"Student {student_name} does not exist.")

def display_all_grades():
    for student, grades in student_grades.items():
        print(f"{student}: {grades}")

add_student("John", {"Math": 85, "Science": 90})
add_student("Alex", {"Math": 78, "History": 88})
update_grade("John", "Math", 95)       # Updates John's Math grade
update_grade("John", "English", 82)    # Adds a new subject for John
get_student_grade("John", "Math")      # Retrieves John's grade for Math
get_student_grade("Alex", "Science")   # Tries to retrieve a non-existing subject
display_all_grades()   

				
			

Explanation: The program starts with creating an empty dictionary. Next, multiple functions are created to add students and their grades, update grades, and retrieve a student’s grades for a specific subject.

add_student: The function is defined with two parameters i.e., student_name, grades. Next, The student name is checked by using the conditional statement, if it is found, then the message is shown as ‘exist’ otherwise the student name is added with its value in the key-value pair to the dictionary.

Update_grade: The function is defined with three parameters i.e., student_name, subject, new_grade. First, we check; 

If the student’s name is present in the dictionary: 

Then it is checked if the subject is present with a particular student name in the dictionary or not. If it is present, the old grade is updated with the new grade by accessing the subject associated with the student’s name.

Otherwise, if the subject is not present in the dictionary, then the respective grade is assigned to the associated subject and added to the dictionary in a key-value pair.

If the student’s name is not present in the dictionary:

A message is displayed of ‘{student name} does not exist’.

get_student_grade: The function is defined with two parameters i.e., student_name, subject.

First, we check; 

If the student’s name is present in the dictionary:

Then it is checked if the subject is present with a particular student name in the dictionary or not. If it is present, a message is displayed to show the grade of a specific subject associated with a student’s name.

Otherwise, if the subject is not present in the dictionary, then a message is shown ‘{subject} is not found associated with a student’s name.

If the student’s name is not present in the dictionary:

A message is displayed of ‘{student name} does not exist’

display_all_grades: A function is created that returns the dictionary containing the student’s name as a key, along with a nested dictionary as a value, showing the subject and its grades.

Next, the required parameters are assigned with the respective values per the requirement to perform the operations based on each function.

Project 4: Inventory Management System

Create a program to manage an inventory of products. The program should allow users to add products, update quantities, and check the stock of a specific product. Each product’s name should be a key, and its quantity should be the value.

				
					def menu():
    print('1. Add products')
    print('2. Update quantities')
    print('3. Check stock of a product')
    print('4. Display prodcuts')
    print('5. Exit')

def add_products(Inventory):
    add_product = input('Enter the product name: ')
    add_product_quantity = input('Enter the quantity: ')
    if add_product in Inventory:
        print(f'{add_product}, is already exist.')
    else:
        Inventory[add_product] = add_product_quantity
        print(f'{add_product}, is added with {add_product_quantity} quantity successfully.')

def update_quantities(Inventory):
    add_product = input('Enter the product name to update quantity: ')
    if add_product in Inventory:
        new_quantity = input('Enter the new quantity :')
        old_quantity = Inventory[add_product]
        Inventory[add_product] = new_quantity
        print(f'{add_product} quantity is updated from {old_quantity} to {new_quantity}')
    else:
        print(f'{add_product} does not exist in the Inventory.')

def check_stock(Inventory):
    add_product = input('Enter the product name to check stock: ')
    if add_product in Inventory:
        print(f'{add_product} quantity :{Inventory[add_product]} in stock.')
    else:
        print(f'{Inventory} does not exist in Inventory Management System.')

def display_inventory(Inventory):
    print(f'Here is the Inventory List: {Inventory}')
    return display_inventory

Inventory = {}

while True:
    menu()
    choose_num = input('Choose a number: 1. 2. 3. 4. 5.')

    if choose_num == '1':
        add_products(Inventory)
    elif choose_num == '2':
        update_quantities(Inventory)
    elif choose_num == '3':
        check_stock(Inventory)
    elif choose_num == '4':
        display_inventory(Inventory)

    elif choose_num == '5':
        print('Exit!')
        break
    else:
        print('Invalid Number! Try Again...')
				
			

Explanation: The program starts with creating multiple functions for operations like adding products, updating quantities, and checking the stock of a specific product.

add_products: The function is defined with a parameter i.e., Inventory. The function asks for the product name & the quantity and is checked with the conditional statement if it is present already in the inventory management system. If present, a message is shown as ‘already exist’ otherwise, it is added to the inventory management system by assigning the product name as key to the dictionary with its quantity as value.

update_quantities: The function asks for the product name and checks with the conditional statement if it is already present in the inventory management system (dictionary). If present, a new quantity is assigned by the user to the dictionary. If the product is not present in the dictionary, then a message is shown ‘does not exist.’ 

check_stock: The function asks for the product name and checks with the conditional statement if it is already present in the inventory management system (dictionary). If present, a message is shown with the product name and its quantity, otherwise, ‘product does not exist’

display_inventory: A function is created that returns the dictionary containing the product as key and its quantity as value.

Now, the Python while loop is used to let the user choose the option and based on that according to the conditional statement the function is called with the matched condition.

Project 5: Translation Dictionary

Write a program that creates a simple translation dictionary. The program should allow users to add words in one language as keys and their translations as values, look up translations and update existing translations.

				
					translation_dict = {}

while True:
    print("1. Add a new translation")
    print("2. Look up a translation")
    print("3. Update an existing translation")
    print("4. Display all translations")
    print("5. Exit")

    choice = input("Choose an option (1-5): ")

    if choice == '1':
        # Add a new translation
        word = input("Enter the sentence to translate: ").strip()
        translation = input("Enter its translation: ").strip()

        if word in translation_dict:
            print(f'The sentence {word} --> already exist in the dictionary.')
        else:
            translation_dict[word] = translation
            print(f"Added: '{word}' -> '{translation}'")
    
    elif choice == '2':
        # Look up a translation
        word = input("Enter the sentence to translate: ").strip()
        if word in translation_dict:
            print(f'Translation of sentence {word}:{translation_dict[word]}')
        else:
            print(f'The sentence {word} --> does not exist in the dictionary.')

    elif choice == '3':
        # Update an existing translation
        word = input("Enter the sentence to translate: ").strip()
        if word in translation_dict:
            new_translation = input("Enter its translation: ").strip()
            translation_dict[word] = new_translation
            print(f"Updated: '{word}' -> '{new_translation}'")
        else:
            print(f"'{word}' is not in the dictionary, so it can't be updated.")
    
    elif choice == '4':
        #Display all translations
        if translation_dict:
            for word, translation in translation_dict.items():
                print(f'{word}:{translation}')
        else:
            print("The dictionary is empty.")

    elif choice == '5':
        # Exit the program
        print("Exiting the program.")
        break

    else:
        print("Invalid option. Please choose a number between 1 and 5.")
				
			

Explanation: The program starts with an empty dictionary which stores the word as key and its translation as value.

Next, the program takes command with the Python while loop in which the user is allowed with some options to perform the operations in the dictionary. So, based on the user’s choice, the conditions will be checked and the matched condition will be executed.

If choice = 1

The word and its translations are asked to the user and the strip() function is used to remove any whitespace and punctuation. The Python conditional statement checks if the word is in the dictionary already, then the word is shown otherwise, the word and its translation are added to the dictionary.

Otherwise, if choice = 2

The word is asked to the user. The Python conditional statement checks if the word is in the dictionary already, then the word and its translations are shown otherwise, the message is shown as ‘word does not exist.’

Otherwise, if choice = 3

The word is asked to the user. The Python conditional statement checks if the word is in the dictionary already, then the new translation is asked for the word and is assigned the word (translation is updated with the old translation value), if the word is not present, a message is shown ‘word is not in the dictionary’

Otherwise, if choice = 4

Using the Python for loop, the whole dictionary is displayed by using the items() function which returns the set of the key-value pairs. Otherwise, the message is shown ‘dictionary is empty’.

Otherwise, if choice = 5

The program/while loop is stopped using the break keyword.

Otherwise, 

If the user chooses any other number from the given options, the program asks again the user to enter the number by showing a message, ‘invalid option.’

Recent Articles