A2SV Python Track - DS Basics 2 - Sets and Dictionaries
A2SV Python Track - DS Basics 2 - Sets and Dictionaries
● Curly braces { }
● Sets in Python use a hash table to store elements which is like a big storage
box with lots of compartments (buckets).
● When you add an element to the set, a special function (hash function) turns
the element into a unique code that determines which bucket the element
goes into.
● When you want to check if an element is in the set (lookup), the hash
function is used again to find the compartment where that element should
be.
Access Elements
● You cannot access items in a set by referring to an index or a key.
● To check if an item is in a set, you use the in operator.
my_set = {1, 2, 3, 4, 5}
if 3 in my_set:
#code
● You can iterate through all items in a set using a for-in loop
for item in my_set:
#code
Add And Remove Elements
● The add() method is used to add a single element to a set.
● The update() method is used to add multiple elements using iterables
(lists, tuples)
● The union() method Return a set containing the union of sets
my_set = set()
my_set.add(1) my_set.update([3, 4, 5, 6])
my_set.add(2) print(my_set) # {1, 2, 3, 4, 5, 6}
my_set.add(3)
print(my_set) # {1,2,3}
Add And Remove Elements
● The clear() method Removes all the elements from the set.
● The remove() and discard() methods Remove the specified item.
● pop() Removes an element from the set.
● Intersection (&)
intersection_set = set1 & set2
● Difference (-)
difference_set = set1 - set2
Valid Operators
Symmetric Difference (^)
symmetric_difference_set = set1 ^ set2
Equality(==)
set1 == set2
Invalid Operators
● Concatenation (+)
● Multiplication (*)
● Indexing ([]) and Slicing ([:])
Set Comprehension
1. Uniqueness of Elements
2. Fast Membership Testing
3. Mathematical Set Operations
Frozenset
● a frozenset is an immutable and hashable version of a set.
frozen_set = frozenset([1, 2, 3])
frozen_set = frozenset([1, 2, 3])
frozen_set.add(4) # possible?
union_frozenset = frozenset1 | frozenset2 # possible?
intersection_frozenset = frozenset1 & frozenset2 # possible?
Exercises
1. Check if All the Integers in a Range Are Covered - LeetCode
2. Union of two arrays | Practice | GeeksforGeeks
3. Check if two arrays are equal or not | Practice | GeeksforGeeks
4. Array Subset of another array | Practice | GeeksforGeeks
Dictionaries
What Is Dictionary?
Dictionary
● Curly braces { }
dictionary = {'name': 'John', 'age': 30, 'city': 'New York'}
● Dictionary comprehension
sqr_dict = {num: num**2 for num in range(1, 11)}
What data types can be used as
dictionary keys in Python?
● Dictionary keys must be immutable data types to maintain data integrity.
● Integers, Floats, Strings,Tuples and Booleans.
● Add or Update
my_dict["age"] = 20
my_dict["age"] = my_dict.get("age",0) + 10
● Removing Key
value = my_dict.pop("age")
Common Operations In Dictionary
● Checking if the key exist
if "age" in my_dict
● Iterating
● Through Keys:
for key in my_dict:
● Through key-value pairs:
for key, value in my_dict.items():
● Through values:
for value in my_dict.values():
Dictionary Copying
● Assignment Operator (=):
my_dict1 = {'key1': 'value1', 'key2': 'value2'}
my_dict2 = my_dict1
my_dict2[‘key1’] = ‘value3’
print(my_dict1) # Output?
● Note: In Python, when you use the assignment operator (=) to assign any
object to another variable, both variables reference the same underlying
iterable in memory. modifications made to the iterable through one variable
will be visible when accessing the iterable through the other variable, and
vice versa.
Shallow Copy
● A shallow copy creates a new dictionary but does not create new
copies of the objects inside the dictionary.
● Changes made to mutable objects (like lists) within the original
dictionary will affect the corresponding objects in the copied
dictionary, and vice versa.
Shallow Copy
original_dict['key1'].append('value3')
Original_dict['key2'] = ‘value4’
print(shallow_copied_dict) # Output?
Deep Copy
● A deep copy creates a new dictionary and recursively creates new
copies of all objects inside the original dictionary, including nested
objects.
● Changes made to mutable objects within the original dictionary will
not affect the corresponding objects in the copied dictionary, and
vice versa.
Deep Copy
original_dict['key1'].append('value3')
print(deep_copied_dict) # Output?
Dictionary
Methods
Advantage of Dictionaries
- Jim Rohn