Implementing dictionary-based solutions to real-world scenarios
Welcome to the exciting world of Python dictionary manipulation! In this course, you will learn how to harness the power of dictionaries to solve real-world problems efficiently. Dictionaries are versatile data structures that allow you to store and manipulate data in key-value pairs, making them indispensable for a wide range of programming tasks.
Prerequisites:
- Basic knowledge of Python programming
- Understanding of basic data types (e.g., strings, integers)
Sample Code Example:
# Creating a dictionary
student_scores = {
"Alice": 85,
"Bob": 90,
"Charlie": 75,
"David": 80
}
# Accessing dictionary elements
print(student_scores["Bob"]) # Output: 90
# Adding a new item
student_scores["Eva"] = 88
# Updating an existing item
student_scores["Charlie"] = 78
# Deleting an item
del student_scores["David"]
# Iterating through dictionary
for name, score in student_scores.items():
print(name, ":", score)
Practice Questions:
- Create a dictionary representing a shopping list with items and their quantities.
- Write a program to calculate the average score from a dictionary containing student scores.
- Merge two dictionaries into a single dictionary.
- Sort a dictionary based on its values in ascending order.
- Write a function to find the most common word in a text document using a dictionary.
Solutions:
- Shopping List Dictionary:
shopping_list = {
"Apples": 5,
"Bananas": 3,
"Milk": 2,
"Bread": 1
}
- Average Score Calculation:
def calculate_average(scores):
total = sum(scores.values())
return total / len(scores)
# Example usage:
average_score = calculate_average(student_scores)
print("Average Score:", average_score)
- Merge Dictionaries:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)
- Sort Dictionary by Values:
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print("Sorted Dictionary:", sorted_dict)
- Most Common Word in Text:
def most_common_word(text):
word_counts = {}
for word in text.split():
word = word.lower()
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
return max(word_counts, key=word_counts.get)
# Example usage:
text = "This is a sample text with some repeated words like sample and text"
common_word = most_common_word(text)
print("Most Common Word:", common_word)
This course will equip you with essential skills to leverage Python dictionaries effectively in various applications. Get ready to dive into the world of Python dictionary manipulation and start solving real-world problems like a pro! Let’s get started! 🚀