Set and Dictonary
Set and Dictonary
1. Define
- A set is a collection of unique and unordered elements.
3. Syntax
python
my_set = {element1, element2, element3,..........element n}
4. Create Set
- Use curly braces {} or the set() function.
python
my_set = {1, 2, 3} Using curly braces
my_set = set([1, 2, 3]) Using set() function
5. Access Set
- Sets are unordered, so you cannot access elements by
index. Use loops to access elements.
python
for item in my_set:
print(item)
6. Update Set
- Add elements using add() or update multiple elements using
update().
python
my_set.add(4) Adds a single element
my_set.update([5, 6]) Adds multiple elements
7. Delete Set
- Remove elements using remove(), discard(), or pop(). Clear
the set using clear() or delete it using del.
python
1.my_set.remove(2) Removes a specific element
2.my_set.discard(3) Removes an element (no error if not
found)
3.my_set.pop() Removes a random element
4.my_set.clear() Removes all elements
5.del my_set Deletes the entire set
5 Solvable Examples (Set)
1. Define
- A dictionary is a collection of key-value pairs.
3. Syntax
python
my_dict = {"key1": "value1", "key2": "value2"}
4. Create Dictionary
- Use curly braces {} with key: value pairs or the dict()
function.
python
my_dict = {"name": "Alice", "age": 25} Using curly braces
my_dict = dict(name="Alice", age=25) Using dict() function
5. Access Dictionary
- Access values using keys.
python
print(my_dict["name"]) Output: Alice
6. Update Dictionary
- Add or modify key-value pairs.
python
my_dict["age"] = 30 Updates the value of "age"
my_dict["city"] = "New York" Adds a new key-value pair
Example:
student = {'name': 'John', 'age': 20, 'grade': 'A'}
student['age'] = 21 # updating the value of 'age'
print("Updated dictionary:", student)
7. Delete Dictionary
- Remove key-value pairs using pop(), popitem(), or del. Clear
the dictionary using clear() or delete it using del.
python
1.my_dict.pop("age") Removes the key "age"
2.my_dict.popitem() Removes the last inserted key-value
pair
3.del my_dict["name"] Removes the key "name"
4.my_dict.clear() Removes all key-value pairs
5.del my_dict Deletes the entire dictionary
5 Solvable Examples (Dictionary)
Set
1. Find the intersection of two sets: {1, 2, 3} and {3, 4, 5}.
2. Check if {1, 2} is a subset of {1, 2, 3, 4}.
3. Remove a random element from the set {10, 20, 30, 40}.
4. Add multiple elements [5, 6, 7] to the set {1, 2, 3}.
5. Convert a list [1, 2, 2, 3, 4] into a set and print it.
Dictionary
1. Merge two dictionaries: {"a": 1, "b": 2} and {"c": 3, "d": 4}.
2. Check if the key "name" exists in the dictionary {"name":
"Alice", "age": 25}.
3. Update the value of the key "age" to 30 in the dictionary
{"name": "Alice", "age": 25}.
4. Remove the last inserted key-value pair from the dictionary
{"name": "Alice", "age": 25, "city": "New York"}e.
5. Create a dictionary where keys are numbers from 1 to 5
and values are their squares.