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)
Set Operations
Python provides mathematical operations for working with sets.
Example:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B)
print(A & B)
print(A - B)
print(A ^ B)
Other Set Methods
Example:
fruits = {"apple", "banana", "cherry"}
print(fruits)
fruits.add("mango")
print(fruits)
fruits.update(["orange", "grape"])
print(fruits)
fruits.remove("banana")
print(fruits)
fruits.discard("papaya")
print(fruits)
copied_set = fruits.copy()
print(copied_set)
fruits.clear()
print(fruits)
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"])
print(person.get("age"))
Adding and Updating Values
You can add new key-value pairs or modify existing ones easily:
person["city"] = "New York"
person["age"] = 26
To remove items:
person.pop("profession")
person.clear()
Dictionary Methods
Example:
person = {"name": "John", "city": "New York", "profession": "Engineer"}
print(person)
print("Keys:", person.keys())
print("Values:", person.values())
print("Items (key-value pairs):", person.items())
person.update({"age": 30, "city": "Los Angeles"})
print("After update:", person)
removed_value = person.pop("age")
print("After pop('age'):", person, "| Removed value:", removed_value)
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.
In the next article, we'll explore Functions in Python — how to define, call, and reuse blocks of code effectively.
Comments
No comments yet. Ask a question or share what helped.