Monday, October 23, 2023

Unlocking Python Dictionaries: Your Guide to Key-Value Pairs 📖

  • Dictionaries are versatile data structures in Python that go beyond simple key-value pairs. In this comprehensive guide, we'll start with the basics of dictionaries and then dive into advanced techniques. 
  • By the end, you'll wield the power of dictionaries to manage complex data in your Python programs with ease.

1. What Is a Dictionary?

  • A dictionary is a collection of key-value pairs, where each key is unique and linked to a specific value.

2. Creating Dictionaries

  • Dictionaries can be created using curly braces {} or the dict() constructor.

my_dict = {'name': 'Alice', 'age': 30}

3. Adding and Accessing Elements

  • You can add, access, and update elements using their keys.

my_dict = {'name': 'Alice', 'age': 30} name = my_dict['name'] my_dict['age'] = 31

4. Modifying and Deleting Elements

  • Modify or delete items in your dictionary by specifying their keys.

my_dict = {'name': 'Alice', 'age': 30} my_dict['age'] = 31 del my_dict['name']

5. Common Dictionary Operations

  • Operations include finding the number of key-value pairs, checking if a key exists, and clearing the dictionary.

my_dict = {'name': 'Alice', 'age': 30} num_items = len(my_dict) exists = 'name' in my_dict my_dict.clear()

6. Nested Dictionaries

  • Create complex data structures by nesting dictionaries within each other.

my_dict = {'person': {'name': 'Alice', 'age': 30}} name = my_dict['person']['name']

7. Dictionary Methods

  • Dictionaries offer methods like get(), keys(), values(), and items() for various operations.
  • get(): Retrieve values using a key or a default value if the key is not found.

my_dict = {'name': 'Alice', 'age': 30} name = my_dict.get('name', 'Unknown')
  • keys(): Get a list of all the keys in the dictionary.

my_dict = {'name': 'Alice', 'age': 30} keys = my_dict.keys()
  • values(): Get a list of all the values in the dictionary.

my_dict = {'name': 'Alice', 'age': 30} values = my_dict.values()
  • items(): Get a list of key-value pairs as tuples.

my_dict = {'name': 'Alice', 'age': 30} items = my_dict.items()

8. Looping Through Dictionaries

  • Use loops to iterate through keys, values, or both.

my_dict = {'name': 'Alice', 'age': 30} for key, value in my_dict.items(): print(key, value)

9. Use Cases for Dictionaries

  • Explore real-world scenarios where dictionaries shine, like building a word frequency counter or storing user information.

10. Advanced Dictionary Techniques

  • Default Values: With setdefault(), you can provide default values for keys that might not exist yet.

my_dict = {} value = my_dict.setdefault('name', 'Unknown')
  • Dictionary Comprehensions: Generate dictionaries using concise one-liners.

squared_dict = {x: x**2 for x in range(5)}

12.Exercise_1 - Python Tuple Operations Application

Project Description:
  • The Python Dictionaries Operation Application is a Python program that provides an interactive interface for users to create, modify, and manage dictionaries, which are an essential data structure in Python. 
  • The application covers various dictionary operations, including adding and accessing elements, modifying and deleting elements, working with nested dictionaries, using dictionary methods like get, keys, values, items, looping through dictionaries, handling dictionaries with default values, and utilizing dictionary comprehensions.
Project Scope:
  • The project encompasses the following key features related to Python dictionaries:
Interactive User Interface:
  • The application provides an interactive user interface for users to perform dictionary operations.
Initial Dictionary Setup:
  • The application initializes the dictionary with some predefined key-value pairs to provide a starting point for users.
Adding and Accessing Elements:
  • Users can add new key-value pairs to the dictionary and access values using keys.
Modifying and Deleting Elements:
  • The system allows users to modify the values associated with keys and delete key-value pairs from the dictionary.
Nested Dictionaries:
  • The application demonstrates the creation and manipulation of nested dictionaries, where values can be dictionaries themselves.
Dictionary Methods - get:
  • Users can use the get method to safely access dictionary values, with an optional default value if the key does not exist.
Dictionary Methods - keys:
  • The application enables users to extract a list of keys from dictionaries using the keys method.
Dictionary Methods - values:
  • Users can retrieve a list of values from dictionaries using the values method.
Dictionary Methods - items:
  • The application allows users to obtain a list of key-value pairs as tuples using the items method.
Looping Through Dictionaries:
  • The application demonstrates how to iterate through dictionaries using various loop constructs.
Dictionary with Default Values:
  • Users can see how dictionaries with default values are handled, especially when retrieving values for non-existing keys.
Dictionary Comprehensions:
  • Users have the option to create dictionaries using dictionary comprehensions to filter and manipulate data efficiently.
Below is  code for the Python Dictionaries Operation Application that meets the above specified requirements.
# Python Dictionaries Operation Application
# Initialize an empty dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York",
"email": "john@example.com"
}

# Function to add key-value pairs to the dictionary
def add_to_dictionary():
key = input("Enter a key: ")
value = input("Enter a value: ")
my_dict[key] = value
print(f"Key-Value pair '{key}': '{value}' added to the dictionary.")

# Function to access values using keys
def access_dictionary():
key = input("Enter a key to access its value: ")
if key in my_dict:
value = my_dict[key]
print(f"The value for key '{key}' is '{value}'.")
else:
print(f"Key '{key}' not found in the dictionary.")

# Function to modify values in the dictionary
def modify_dictionary():
key = input("Enter a key to modify its value: ")
if key in my_dict:
value = input(f"Enter the new value for key '{key}': ")
my_dict[key] = value
print(f"Value for key '{key}' updated to '{value}'.")
else:
print(f"Key '{key}' not found in the dictionary.")

# Function to delete key-value pairs from the dictionary
def delete_from_dictionary():
key = input("Enter a key to delete: ")
if key in my_dict:
del my_dict[key]
print(f"Key-Value pair '{key}': '{my_dict[key]}' deleted from the dictionary.")
else:
print(f"Key '{key}' not found in the dictionary.")

# Function to demonstrate nested dictionaries
def nested_dictionaries():
nested_dict = {}
key = input("Enter a key for the nested dictionary: ")
nested_key = input("Enter a key for the nested value: ")
nested_value = input("Enter a value for the nested key: ")
nested_dict[nested_key] = nested_value
my_dict[key] = nested_dict
print(f"Nested dictionary added under key '{key}'.")

# Function to use the dictionary method get
def dictionary_get():
key = input("Enter a key to access its value using 'get': ")
value = my_dict.get(key, "Key not found")
print(f"The value for key '{key}' (using 'get') is '{value}'.")

# Function to display dictionary keys
def display_keys():
keys = my_dict.keys()
print("Keys in the dictionary:", list(keys))

# Function to display dictionary values
def display_values():
values = my_dict.values()
print("Values in the dictionary:", list(values))

# Function to display dictionary items
def display_items():
items = my_dict.items()
print("Key-Value pairs in the dictionary:", list(items))

# Function to demonstrate looping through dictionaries
def loop_through_dictionary():
print("Looping through the dictionary:")
for key, value in my_dict.items():
print(f"Key: '{key}', Value: '{value}'")

# Function to create a dictionary with default values
def default_value_dictionary():
from collections import defaultdict
default_dict = defaultdict(int)
print("Default dictionary created with default integer values.")
print("Sample usage: default_dict['key'] will return 0 if the key doesn't exist.")

# Main application loop
while True:
print("\nPython Dictionaries Operation Application")
print("1. Add to Dictionary")
print("2. Access Dictionary")
print("3. Modify Dictionary")
print("4. Delete from Dictionary")
print("5. Nested Dictionaries")
print("6. Dictionary Method - Get")
print("7. Dictionary Method - Keys")
print("8. Dictionary Method - Values")
print("9. Dictionary Method - Items")
print("10. Loop Through Dictionary")
print("11. Dictionary with Default Values")
print("12. Exit")

choice = input("Enter your choice (1/2/3/4/5/6/7/8/9/10/11/12): ")

if choice == '1':
add_to_dictionary()
elif choice == '2':
access_dictionary()
elif choice == '3':
modify_dictionary()
elif choice == '4':
delete_from_dictionary()
elif choice == '5':
nested_dictionaries()
elif choice == '6':
dictionary_get()
elif choice == '7':
display_keys()
elif choice == '8':
display_values()
elif choice == '9':
display_items()
elif choice == '10':
loop_through_dictionary()
elif choice == '11':
default_value_dictionary()
elif choice == '12':
print("Exiting the Python Dictionaries Operation Application. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5/6/7/8/9/10/11/12)."

13.Exercise_2 - Library Catalog Management Application

Project Description: 
  • The Library Catalog Management Application is a Python program that provides an interactive interface for users to manage a library catalog. 
  • The application allows users to perform various operations, including adding and updating book details, searching for books, generating catalog reports, borrowing books, returning borrowed books, and viewing a list of borrowed books.
Project Scope: 
  • The project encompasses the following key features related to library catalog management:
Interactive User Interface: 
  • The application provides an interactive user interface for users to perform library catalog operations.
Initial Library Catalog Setup: 
  • The application initializes the library catalog (a dictionary) with some predefined book entries for users to start with.
Adding and Updating Book Details: 
  • Users can add new books to the catalog with details such as the title, author, genre, publication year, and the number of copies available. They can also update book details, including the author, genre, publication year, and the number of copies available.
Searching for Books: 
  • The application allows users to search for books by title, author, or genre, providing a list of matching books.
Generating Catalog Reports: 
  • Users can generate a report of all books in the library catalog, listing book details such as title, author, genre, publication year, and the number of copies available.
Borrowing Books: 
  • Users can borrow books from the catalog. The application tracks the due date for each borrowed book.
Returning Borrowed Books: 
  • Users can return borrowed books, and the application updates the available copies and due dates accordingly.
Viewing Borrowed Books: 
  • Users can view a list of borrowed books, including their titles and due dates.

# Library Catalog Management Application
from datetime import datetime, timedelta
# Initialize the library catalog (dictionary) with some initial books
library_catalog = {
"Book 1": {
"Author": "Author A",
"Genre": "Fiction",
"Year": "2020",
"Copies Available": 3,
"Total Copies": 3,
},
"Book 2": {
"Author": "Author B",
"Genre": "Mystery",
"Year": "2019",
"Copies Available": 2,
"Total Copies": 2,
},
"Book 3": {
"Author": "Author C",
"Genre": "Non-fiction",
"Year": "2021",
"Copies Available": 1,
"Total Copies": 1,
},
}

# Initialize the borrowed books dictionary
borrowed_books = {
"Book 4": "2023-10-15",
}

# Function to add a book to the library catalog
def add_book():
title = input("Enter the title of the book: ")
author = input("Enter the author's name: ")
genre = input("Enter the genre: ")
year = input("Enter the publication year: ")
copies = int(input("Enter the number of copies available: "))

if title not in library_catalog:
book_details = {
"Author": author,
"Genre": genre,
"Year": year,
"Copies Available": copies,
"Total Copies": copies,
}
library_catalog[title] = book_details
print(f"Book '{title}' added to the library catalog.")
else:
print(f"Book '{title}' already exists in the catalog.")

# Function to update book details in the library catalog
def update_book():
title = input("Enter the title of the book to update: ")
if title in library_catalog:
print("Select the detail to update:")
print("1. Author")
print("2. Genre")
print("3. Publication Year")
print("4. Number of Copies")
choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
author = input("Enter the new author's name: ")
library_catalog[title]["Author"] = author
elif choice == '2':
genre = input("Enter the new genre: ")
library_catalog[title]["Genre"] = genre
elif choice == '3':
year = input("Enter the new publication year: ")
library_catalog[title]["Year"] = year
elif choice == '4':
copies = int(input("Enter the new number of copies available: "))
library_catalog[title]["Copies Available"] = copies
library_catalog[title]["Total Copies"] = copies
else:
print("Invalid choice.")
print(f"Book '{title}' details updated successfully.")
else:
print(f"Book '{title}' not found in the catalog.")

# Function to borrow a book
def borrow_book():
title = input("Enter the title of the book to borrow: ")
if title in library_catalog:
if library_catalog[title]["Copies Available"] > 0:
if title not in borrowed_books:
due_date = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
borrowed_books[title] = due_date
library_catalog[title]["Copies Available"] -= 1
print(f"Book '{title}' borrowed successfully. Due date: {due_date}")
else:
print(f"Book '{title}' is already borrowed. Due date: {borrowed_books[title]}")
else:
print(f"No copies of '{title}' are available for borrowing.")
else:
print(f"Book '{title}' not found in the catalog.")

# Function to return a borrowed book
def return_book():
title = input("Enter the title of the book to return: ")
if title in borrowed_books:
due_date = borrowed_books[title]
return_date = input(f"Enter the return date (yyyy-mm-dd) for '{title}' (due date: {due_date}): ")
if return_date <= due_date:
library_catalog[title]["Copies Available"] += 1
del borrowed_books[title]
print(f"Book '{title}' returned successfully.")
else:
print(f"Book '{title}' is overdue. Return not allowed.")
else:
print(f"Book '{title}' is not in the list of borrowed books.")

# Function to search for books in the library catalog
def search_books():
search_term = input("Enter a title, author, or genre to search for books: ")
found_books = []

for title, details in library_catalog.items():
if (search_term.lower() in title.lower()) or (search_term.lower() in details["Author"].lower()) or (
search_term.lower() in details["Genre"].lower()):
found_books.append((title, details))

if found_books:
print("Matching Books:")
for book in found_books:
print(f"Title: {book[0]}")
print(f"Author: {book[1]['Author']}")
print(f"Genre: {book[1]['Genre']}")
print(f"Publication Year: {book[1]['Year']}")
print(f"Copies Available: {book[1]['Copies Available']} / Total Copies: {book[1]['Total Copies']}")
print()
else:
print("No matching books found in the catalog.")

# Function to generate a report of books in the library catalog
def generate_report():
print("Library Catalog Report:")
for title, details in library_catalog.items():
print(f"Title: {title}")
print(f"Author: {details['Author']}")
print(f"Genre: {details['Genre']}")
print(f"Publication Year: {details['Year']}")
print(f"Copies Available: {details['Copies Available']} / Total Copies: {details['Total Copies']}")
print()

# Function to view borrowed books
def view_borrowed_books():
if borrowed_books:
print("Borrowed Books:")
for title, due_date in borrowed_books.items():
print(f"Title: {title}, Due Date: {due_date}")
else:
print("No books have been borrowed.")

# Main application loop
while True:
print("\nLibrary Catalog Management Application")
print("1. Add Book")
print("2. Update Book Details")
print("3. Search for Books")
print("4. Generate Catalog Report")
print("5. Borrow a Book")
print("6. Return a Borrowed Book")
print("7. View Borrowed Books")
print("8. Exit")

choice =
input("Enter your choice (1/2/3/4/5/6/7/8): ")

if choice == '1':
add_book()
elif choice == '2':
update_book()
elif choice == '3':
search_books()
elif choice == '4':
generate_report()
elif choice == '5':
borrow_book()
elif choice == '6':
return_book()
elif choice == '7':
view_borrowed_books()
elif choice == '8':
print("Exiting the Library Catalog Management Application. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5/6/7/8).")

14.Exercise_3 - Auction Application

Conclusion

  • Dictionaries in Python are powerful data structures that can manage complex data effectively. By mastering both the basics and advanced techniques, you can handle diverse data scenarios in your Python programs. 📖🐍

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS