Dictionaries and sets are important data structures in Python that expand your data manipulation capabilities.
A dictionary is an unordered collection of key-value pairs. You can access values in a dictionary using their corresponding keys.
# Example of a dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# Accessing values using keys
print(person["name"]) # Output: John Doe
print(person["age"]) # Output: 30
print(person["city"]) # Output: New York
A set is an unordered collection of unique elements. It does not allow duplicate values.
# Example of a set
fruits = {"apple", "banana", "orange", "apple"}
# Note that duplicate values are automatically removed
print(fruits) # Output: {'apple', 'banana', 'orange'}
Exercise: Given a list of numbers, create a dictionary with the number as the key and its square as the value. Then, convert the dictionary values into a set and print the unique squares.
Follow these steps to work on the exercise:
# Exercise: Creating a dictionary and converting values into a set
numbers = [1, 2, 3, 4, 5, 3]
squares_dict = {num: num ** 2 for num in numbers}
squares_set = set(squares_dict.values())
print("Original List of Numbers:", numbers)
print("Dictionary of Number-Squares:", squares_dict)
print("Unique Squares in Set:", squares_set)
Dictionaries and sets are powerful data structures that enable efficient data manipulation and ensure uniqueness in the case of sets. Practice working with dictionaries and sets to enhance your data processing skills in Python.