Dictionaries and Sets in Python

Dictionaries and sets are important data structures in Python that expand your data manipulation capabilities.

Dictionaries (Key-Value Pairs):

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
        
    

Sets (Unordered Collection with Unique Elements):

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'}
        
    

Dictionaries and Sets Exercise:

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:

  1. Create a list of numbers with some duplicates, for example, [1, 2, 3, 4, 5, 3].
  2. Write a Python script to create a dictionary where each number is a key, and its square is the corresponding value.
  3. Use the set() function to convert the dictionary values into a set of unique squares.
  4. Print the original list of numbers, the dictionary of number-squares, and the unique squares in the set.
  5. Run your Python script and verify the results.

        
            # 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.

Python Sets And Dictionaries YouTube Video