Data Structures: Dictionaries
Welcome to our course on Data Structures, where we’ll explore one of the most important concepts in computer science: Dictionaries. Dictionaries are like magic bags where you can store items and label them with unique tags. In computer science, we call these tags “keys” and the items they label “values.” This course will teach you all about dictionaries, how they work, and how you can use them to solve problems in Python.
Course Outline:
- Introduction to Dictionaries:
- Understanding the concept of key-value pairs.
- Comparing dictionaries to real-life scenarios (like a phone book or a recipe book).
- Basic syntax and operations in Python.
- Creating and Accessing Dictionaries:
- Dictionary Methods:
- Dictionary Manipulation Techniques:
- Practice Questions:
Python Code Examples:
# Creating a dictionary
phone_book = {'Alice': '123-4567', 'Bob': '987-6543', 'Charlie': '456-7890'}
# Accessing values using keys
print(phone_book['Alice']) # Output: 123-4567
# Adding a new entry
phone_book['David'] = '789-0123'
# Updating an existing entry
phone_book['Bob'] = '111-2222'
# Deleting an entry
del phone_book['Charlie']
# Dictionary methods
print(phone_book.keys()) # Output: dict_keys(['Alice', 'Bob', 'David'])
print(phone_book.values()) # Output: dict_values(['123-4567', '111-2222', '789-0123'])
print(phone_book.items()) # Output: dict_items([('Alice', '123-4567'), ('Bob', '111-2222'), ('David', '789-0123')])
# Merging dictionaries
new_contacts = {'Eve': '222-3333', 'Frank': '444-5555'}
phone_book.update(new_contacts)
# Dictionary comprehension
squares = {x: x*x for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Practice Questions:
- Create a dictionary representing a student’s grades in different subjects. Add, update, and delete grades for various subjects.
- Write a Python program to sort a dictionary by key.
- Create a dictionary representing a grocery list. Merge it with another dictionary representing a list of items you already have at home.
Practice Solutions:
- Student Grades Dictionary:
student_grades = {'Math': 90, 'Science': 85, 'History': 70}
student_grades['English'] = 80 # Adding a new subject
student_grades['Math'] = 95 # Updating Math grade
del student_grades['History'] # Deleting History subject
- Sorting Dictionary by Key:
student_grades = {'Math': 90, 'Science': 85, 'History': 70}
sorted_grades = {subject: grade for subject, grade in sorted(student_grades.items())}
- Grocery List Merge:
grocery_list = {'Apples': 5, 'Bananas': 3, 'Milk': 2}
items_at_home = {'Milk': 1, 'Bread': 1, 'Eggs': 6}
grocery_list.update(items_at_home)
By the end of this course, you’ll become a master of dictionaries and be able to use them confidently to solve various problems in Python. So, get ready to dive into the magical world of key-value pairs! Happy coding!