Dictionaries and Sets

Dictionaries and sets are two essential data structures in Python used for efficient data storage and retrieval. This tutorial provides an overview of dictionaries and sets, including their creation, manipulation, and unique characteristics.

Dictionaries

A dictionary is an unordered collection of key-value pairs. Each key is unique and used to access its corresponding value. Dictionaries are mutable, allowing you to modify their contents after creation.

Creating a Dictionary

You can create a dictionary in Python by enclosing key-value pairs within curly braces {}.


      # Creating a dictionary of person details
      person = {
          "name": "John Doe",
          "age": 30,
          "occupation": "Engineer"
      }
      

Accessing Values

You can access the values in a dictionary using their corresponding keys.


      # Accessing the value for the key "name"
      person_name = person["name"]  # Output: "John Doe"

      # Accessing the value for the key "age"
      person_age = person["age"]  # Output: 30
      

Modifying Values

Dictionaries are mutable, so you can modify the values associated with keys after creation.


      # Modifying the age value
      person["age"] = 31
      print(person)  # Output: {'name': 'John Doe', 'age': 31, 'occupation': 'Engineer'}
      

Dictionary Methods

Python provides various methods to manipulate dictionaries:


      # Adding a new key-value pair
      person["city"] = "New York"

      # Removing a key-value pair by key
      del person["occupation"]

      # Checking if a key exists in the dictionary
      if "city" in person:
          print("City information available")
      

Sets

A set is an unordered collection of unique elements. Sets are mutable, allowing you to add or remove elements after creation.

Creating a Set

You can create a set in Python by enclosing elements within curly braces {} or using the set() function.


      # Creating a set with curly braces
      fruits = {"apple", "banana", "orange"}

      # Creating a set with set() function
      colors = set(["red", "green", "blue"])
      

Adding and Removing Elements

You can add and remove elements from a set using various methods.


      # Adding an element to the set
      fruits.add("grape")

      # Removing an element from the set
      fruits.remove("banana")
      

Set Operations

Sets support various operations like union, intersection, and difference.


      # Union of two sets
      all_items = fruits.union(colors)

      # Intersection of two sets
      common_items = fruits.intersection(colors)

      # Difference between two sets
      unique_colors = colors.difference(fruits)
      

Summary

Dictionary Set
Mutable Mutable
Ordered from Python 3.7 onwards Unordered
Indexing/slicing supported Indexing/slicing unsupported
Duplicate keys not allowed, duplicate values allowed Duplicate elements not allowed