HTML

    Select a Subtopic

    Day 5: Dictionaries and String Manipulation

    Master Python dictionaries and string operations with examples and exercises.

    Dictionaries: Key-Value Pairs

    A dictionary in Python is a collection of key-value pairs. It's similar to a real-life dictionary where you look up a word (key) to find its definition (value).

    1 2 3 4 5 6 student_grades = { "Alice": 85, "Bob": 92, "Charlie": 78 } print(student_grades)

    Here’s how you can create, access, add, and remove elements from a dictionary.

    1 2 3 4 5 6 7 8 9 10 # Accessing Values print(student_grades["Alice"]) # Output: 85 # Adding a new student student_grades["David"] = 90 print(student_grades) # Removing a student del student_grades["Charlie"] print(student_grades)

    Iterating through dictionaries:

    1 2 for student, grade in student_grades.items(): print(f"{student}: {grade}")

    String Manipulation

    Python provides powerful tools to work with strings. Let’s explore slicing, formatting, and other string methods.

    1 2 3 text = "Hello, World!" print(text[0:5]) # Output: Hello print(text[-6:]) # Output: World!

    String formatting using f-strings:

    1 2 3 name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.")

    Some common string methods:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 text = " Python is Awesome! " # Convert to uppercase print(text.upper()) # Output: " PYTHON IS AWESOME! " # Convert to lowercase print(text.lower()) # Output: " python is awesome! " # Remove whitespace print(text.strip()) # Output: "Python is Awesome!" # Replace text print(text.replace("Awesome", "Cool")) # Output: " Python is Cool! " # Split text into a list print(text.split()) # Output: ['Python', 'is', 'Awesome!']

    Exercises for Day 5

    Exercise 1: Create a Dictionary of Students and Grades

    Write a program that:

    • Creates a dictionary with student names as keys and their grades as values.
    • Adds a new student to the dictionary.
    • Removes a student from the dictionary.
    • Prints all student names and their grades.

    Exercise 2: Reverse a String

    Write a program that:

    • Takes a string as input.
    • Reverses the string and prints it.
    1 2 3 # Example Input: "Python" Output: "nohtyP"

    Exercise 3: Word Frequency Counter

    Write a program that:

    • Takes a sentence as input.
    • Counts the frequency of each word in the sentence using a dictionary.
    1 2 3 # Example Input: "Python is fun and Python is easy" Output: {'Python': 2, 'is': 2, 'fun': 1, 'and': 1, 'easy': 1}