This tutorial is designed to introduce you to Python's powerful dictionary and set data structures. By the end of this tutorial, you will understand how to create, manipulate, and use dictionaries and sets in Python.
You will learn:
Prerequisites: Basic understanding of Python programming (variables, functions, loops).
A dictionary is a mutable data type that stores mappings of unique keys to values. Here's how you can create a dictionary:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
A set is an unordered collection of unique elements. Here's how to create a set:
my_set = {1, 2, 3, 4, 5}
# Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
# Accessing a value
print(person["name"]) # Output: John
# Updating a value
person["age"] = 31
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
# Adding a new key-value pair
person["profession"] = "Engineer"
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York', 'profession': 'Engineer'}
# Deleting a key-value pair
del person["city"]
print(person) # Output: {'name': 'John', 'age': 31, 'profession': 'Engineer'}
# Creating a set
numbers = {1, 2, 3, 4, 5}
# Adding an element
numbers.add(6)
print(numbers) # Output: {1, 2, 3, 4, 5, 6}
# Removing an element
numbers.remove(1)
print(numbers) # Output: {2, 3, 4, 5, 6}
# Checking if an element exists
print(3 in numbers) # Output: True
In this tutorial, you've learned how to work with dictionaries and sets in Python, including how to create, access, update, and delete elements. Both are powerful data structures that can make your programs more efficient and easier to understand.
Next steps for learning include working with nested dictionaries and sets, as well as exploring other built-in methods available for these data structures.
Exercise 1: Create a dictionary to store information about a book. Include the title, author, year of publication, and number of pages.
Exercise 2: Given a list of numbers, create a set to find and print the unique numbers in the list.
Solutions:
# Exercise 1
book = {
"title": "To Kill a Mockingbird",
"author": "Harper Lee",
"year": 1960,
"pages": 281
}
print(book)
# Exercise 2
numbers = [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8, 9]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
For further practice, try creating more complex dictionaries and sets, and practice manipulating them with the techniques you've learned in this tutorial.