Sets and Dictionaries in Python

In Python, Sets and Dictionaries are powerful data structures used to store collections of data efficiently.

While sets are used for storing unique, unordered elements, dictionaries are used to store data as key-value pairs for fast lookups and organized mappings.

Sets in Python

A set is an unordered collection of unique elements. Sets are defined using { } (curly braces) or the set() function.

Example:

fruits = {"apple", "banana", "cherry"}
print(fruits)
If duplicate elements are added, Python automatically removes them:

numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)   # Output: {1, 2, 3, 4, 5}

Set Operations

Python provides mathematical operations for working with sets.

Operation Description Example
union() or | Combines all unique elements from both sets A.union(B) or A | B
intersection() or & Returns elements common to both sets A.intersection(B) or A & B
difference() or - Elements in one set but not in the other A.difference(B) or A - B
symmetric_difference() or ^ Elements not common to both sets A.symmetric_difference(B) or A ^ B
Example:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union
print(A | B)  # {1, 2, 3, 4, 5, 6}
# Intersection
print(A & B)  # {3, 4}
# Difference
print(A - B)  # {1, 2}
# Symmetric Difference
print(A ^ B)  # {1, 2, 5, 6}

Other Set Methods

Method Description
add() Adds a single element to the set
update() Adds multiple elements
remove() Removes an element (raises error if not found)
discard() Removes an element (no error if missing)
clear() Removes all elements
copy() Returns a shallow copy of the set
Example:

# Initial set
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'banana', 'cherry', 'apple'}
# 1. add()
fruits.add("mango")
print(fruits) # {'banana', 'cherry', 'apple', 'mango'}
# 2. update()
fruits.update(["orange", "grape"])
print(fruits) # {'banana', 'cherry', 'orange', 'apple', 'grape', 'mango'}
# 3. remove()
fruits.remove("banana")
print(fruits) # {'cherry', 'orange', 'apple', 'grape', 'mango'}
# 4. discard()
fruits.discard("papaya")
print(fruits) # {'cherry', 'orange', 'apple', 'grape', 'mango'}
# 5. copy()
copied_set = fruits.copy()
print(copied_set) # {'cherry', 'grape', 'orange', 'apple', 'mango'}
# 6. clear()
fruits.clear()
print(fruits) # set()

Dictionaries in Python

A dictionary stores data in key-value pairs within curly braces { }. Each key must be unique and immutable (e.g., string, number, tuple), while values can be of any type.

Example:

person = {
    "name": "Alice",
    "age": 25,
    "profession": "Engineer"
}
You can access values using their keys:

print(person["name"])     # Output: Alice
print(person.get("age"))  # Output: 25

Adding and Updating Values

You can add new key-value pairs or modify existing ones easily:

person["city"] = "New York"        # Add new key-value
person["age"] = 26                 # Update existing value
To remove items:

person.pop("profession")           # Removes 'profession' key
person.clear()                     # Removes all items

Dictionary Methods

Method Description Example
keys() Returns all keys person.keys()
values() Returns all values person.values()
items() Returns key-value pairs as tuples person.items()
update() Adds or updates multiple key-value pairs person.update({"age": 30})
pop() Removes a key-value pair by key person.pop("age")
clear() Clears all data person.clear()
Example:

# Initial dictionary
person = {"name": "John", "city": "New York", "profession": "Engineer"}
print(person)  # {'name': 'John', 'city': 'New York', 'profession': 'Engineer'}
# 1. keys()
print("Keys:", person.keys())  # Keys: dict_keys(['name', 'city', 'profession'])
# 2. values()
print("Values:", person.values())  # Values: dict_values(['John', 'New York', 'Engineer'])
# 3. items()
print("Items (key-value pairs):", person.items())  # Items (key-value pairs): dict_items([('name', 'John'), ('city', 'New York'), ('profession', 'Engineer')])
# 4. update()
person.update({"age": 30, "city": "Los Angeles"})
print("After update:", person)  # After update: {'name': 'John', 'city': 'Los Angeles', 'profession': 'Engineer', 'age': 30}
# 5. pop()
removed_value = person.pop("age")
print("After pop('age'):", person, "| Removed value:", removed_value)  # After pop('age'): {'name': 'John', 'city': 'Los Angeles', 'profession': 'Engineer'} | Removed value: 30
# 6. clear()
person.clear()
print(person)  # {}

Summary

Sets and Dictionaries are efficient data structures for fast lookups, membership tests, and organizing data. Sets help in mathematical and unique-element operations, while dictionaries provide an intuitive way to map relationships between data.

Understanding both gives you the ability to handle complex data processing with speed and clarity. In the next article, we'll explore Functions in Python โ€” how to define, call, and reuse blocks of code effectively.
Share this Article