whenever life put's you in a tough situtation, never say why me! but, try me!

Data Structures: Sets and Dictionaries

In this module, we will dive into two important data structures in Python: Sets and Dictionaries. Both are widely used for storing collections of data, with each offering unique functionalities that make them ideal for specific use cases. Sets are used when you need unique, unordered collections, while dictionaries provide a way to associate keys with values.


Subtopic 1: Understanding Sets in Python

A set is an unordered collection of unique elements. Unlike lists and tuples, sets do not allow duplicates, and their order is not guaranteed. Sets are highly efficient for operations that involve membership checking, eliminating duplicates, and performing mathematical set operations.

Key Characteristics of Sets:
  • Unordered: The items have no specific order.
  • Unique Elements: Sets automatically remove duplicates.
  • Mutable: You can add and remove items from a set after its creation.
  • Efficient Membership Testing: Checking if an element exists in a set is generally faster than in lists or tuples.
Example:
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Adding elements
my_set.add(6)
my_set.update([7, 8])

# Removing elements
my_set.remove(3)  # Removes 3; raises KeyError if not found
my_set.discard(4)  # Removes 4; doesn't raise an error if not found
my_set.pop()  # Removes and returns a random item

# Set Operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}

# Union
union_set = set_a | set_b  # {1, 2, 3, 4, 5}

# Intersection
intersection_set = set_a & set_b  # {3}

# Difference
difference_set = set_a - set_b  # {1, 2}

# Symmetric Difference
sym_diff_set = set_a ^ set_b  # {1, 2, 4, 5}

# Membership check
print(3 in my_set)  # True

Subtopic 2: Understanding Dictionaries in Python

A dictionary (also known as a dict) is an unordered collection of key-value pairs. The keys are unique and immutable, while the values can be any type of object. Dictionaries are very useful when you need to store and retrieve data based on a unique identifier (key).

Key Characteristics of Dictionaries:
  • Unordered: Items are stored as key-value pairs, but the order is not guaranteed (until Python 3.7).
  • Mutable: You can modify, add, or remove key-value pairs after creation.
  • Efficient Lookups: Retrieving values via their keys is very fast.
  • Keys Must Be Immutable: You can use strings, numbers, or tuples as keys, but not lists or other dictionaries.
Example:
# Creating a dictionary
my_dict = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Accessing values
print(my_dict["name"])  # Output: Alice

# Adding or updating key-value pairs
my_dict["email"] = "alice@example.com"
my_dict["age"] = 31

# Removing items
del my_dict["city"]  # Removes the 'city' key-value pair
my_dict.pop("age")  # Removes and returns the value of the 'age' key

# Checking for a key
print("name" in my_dict)  # True
print("city" in my_dict)  # False

# Dictionary Operations
keys = my_dict.keys()  # Returns a view of keys
values = my_dict.values()  # Returns a view of values
items = my_dict.items()  # Returns a view of key-value pairs

# Iterating over a dictionary
for key, value in my_dict.items():
    print(f"{key}: {value}")

Subtopic 3: Set and Dictionary Operations

Set Operations:
  • Union: Combines two sets, returning a set with all unique elements from both.
  • Intersection: Returns a set with elements that are common to both sets.
  • Difference: Returns a set with elements present in one set but not the other.
  • Symmetric Difference: Returns a set with elements that are in either of the sets, but not in both.
Dictionary Operations:
  • Accessing Values: Values are accessed using keys.
  • Adding and Updating: You can add or update key-value pairs.
  • Deleting Items: Use del or pop to remove key-value pairs.
  • Membership Testing: You can check for the presence of keys using the in keyword.

Subtopic 4: Use Cases for Sets and Dictionaries

Use Cases for Sets:

  • Removing Duplicates: Sets are an excellent way to remove duplicates from a collection.
  • Mathematical Set Operations: Sets are ideal for performing union, intersection, and difference operations on collections of data.
  • Membership Testing: Sets are optimized for checking if an item exists.

Example Use Case:

# Remove duplicates from a list
my_list = [1, 2, 3, 2, 3, 4, 5]
unique_elements = set(my_list)  # {1, 2, 3, 4, 5}

Use Cases for Dictionaries:

  • Data Mapping: Use dictionaries to map keys to values, like storing student names with their scores.
  • Efficient Lookups: Dictionaries provide fast lookups for large datasets.
  • Config Files: Store configuration settings in a dictionary, where the keys are setting names and the values are their values.

Example Use Case:

# Store student grades
grades = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 88
}
# Access Bob's grade
print(grades["Bob"])  # 92

Tasks

  1. Task 1: Set Operations

    • Create two sets, one with numbers from 1 to 5 and another with numbers from 4 to 8. Perform all set operations (union, intersection, difference, and symmetric difference) and print the results.
  2. Task 2: Removing Duplicates

    • Given a list with repeated elements, use a set to remove the duplicates and print the resulting collection.
  3. Task 3: Dictionary Operations

    • Create a dictionary that holds names of countries and their capitals. Add a new country and update an existing capital. Delete a country from the dictionary and print the updated dictionary.
  4. Task 4: Set Use Case

    • Write a Python program to check if a list of students contains any duplicate names. Use a set to check for uniqueness.
  5. Task 5: Dictionary Lookup

    • Create a dictionary with employee names as keys and their salary as values. Write a function to search for an employee’s salary by name. Handle the case where the employee is not found.
  6. Task 6: Nested Data Structures

    • Create a dictionary where the keys are employee names and the values are sets of skills. Write code to add a new skill to an employee's set of skills and print the updated dictionary.