UNIT-III:
Dictionaries in
Python
Python
dictionary is
a data structure that stores the value in key: value pairs.
Values in a dictionary can be of any data type and can be duplicated, whereas
keys can't be repeated and must be immutable.
Example: Here, The data is stored in key : value pairs in dictionaries,
which makes it easier to find values.
Syntax for creating a Python
dictionary:
dictionary_name = {key1: value1, key2: value2, key3: value3}
Explanation of elements:
- dictionary_name: This is the variable name
assigned to the dictionary.
- {}: Curly braces enclose the entire
dictionary content.
- key: A unique identifier used to access
its corresponding value. Keys must be immutable types (e.g.,
strings, numbers, tuples).
- value: The data associated with
a key. Values can be of any data type (e.g., strings, numbers,
lists, other dictionaries).
- : (colon): Separates
a key from its value.
- , (comma): Separates individual
key-value pairs within the dictionary.
CODE:
d = {1: 'Dear', 2: 'Python',
3: 'students'}
print(d)
OUTPUT:
{1: 'Dear', 2: 'Python',
3: 'students'}
How
to Create a Dictionary
Dictionary
can be created by placing a sequence of elements within curly {} braces,
separated by a 'comma'.
CODE:
d1 = {1: 'Dear', 2: 'Python',
3: 'Students'}
print(d1)
# create dictionary using
dict() constructor
d2 = dict(a =
"Dear", b = "Python", c = "Students")
print(d2)
OUTPUT:
{1: 'Dear', 2: 'Python',
3: 'Students'}
{'a': 'Dear', 'b':
'Python', 'c': 'Students'}
- Dictionary keys are case sensitive: the
same name but different cases of Key will be treated distinctly.
- Keys must be immutable: This means keys
can be strings, numbers or tuples but not lists.
- Keys must be unique: Duplicate keys are
not allowed and any duplicate key will overwrite the previous value.
- Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be performed
in Constant Time.
CODE:
# Empty dictionary
my_dict = {}
# Dictionary with initial values
student = {
"name": "John",
"age": 21,
"course": "Computer Science"
}
print(student)
OUTPUT:
{'name': 'John', 'age': 21, 'course': 'Computer Science'}
Adding
and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using
assignment.
CODE:
d = {1: 'Dear', 2: 'Python', 3: 'students'}
# Adding a new key-value pair
d["marks"] = 22
# Updating an existing value
d[1] = "Python class"
print(d)
OUTPUT:
{1: 'Python class', 2: 'Python', 3: 'students', 'marks': 22}
Accessing Dictionary
Values
Values are accessed
using keys.
CODE:
student = {"name":
"John", "age": 21, "course": "CS"}
print(student["name"])
print(student.get("age"))
OUTPUT:
John
21
Modifying Key: Value
Pairs
- Dictionaries are mutable →
values can be changed, and new pairs can be added.
CODE:
student = {"name":
"John", "age": 21}
student["age"] =
22 # Modify existing value
student["grade"] =
"A" # Add new key:value pair
print(student)
OUTPUT:
{'name': 'John', 'age':
22, 'grade': 'A'}
Removing
Dictionary Items
We can remove items
from dictionary using the following methods:
- del: Removes an item by key.
- pop(): Removes an item by key and
returns its value.
- clear(): Empties the dictionary.
- popitem(): Removes
and returns the last key-value pair.
CODE:
d = {1: 'dear', 2: 'python',
3: 'students', 'marks':22}
# Using del to remove an
item
del d["marks"]
print(d)
# Using pop() to remove
an item and return the value
val = d.pop(1)
print(val)
# Using popitem to
removes and returns
# the last key-value
pair.
key, val = d.popitem()
print(f"Key: {key},
Value: {val}")
# Clear all items from
the dictionary
d.clear()
print(d)
OUTPUT:
{1: 'dear', 2: 'python',
3: 'students'}
dear
Key: 3, Value: students
{}
Built-in Functions Used on Dictionaries
|
Function |
Description |
Example |
|
len(dict) |
Number of items |
len(student) → 3 |
|
type(dict) |
Type of object |
type(student) →
<class 'dict'> |
|
str(dict) |
String representation |
str(student) →
"{'name': 'John', ...}" |
CODE:
student = {"name":
"John", "age": 22, "grade": "A"}
print(len(student)) # 3
print(type(student)) # <class 'dict'>
print(str(student)) # {'name': 'John', 'age':
22, 'grade': 'A'}
OUTPUT:
3
<class 'dict'>
{'name': 'John', 'age':
22, 'grade': 'A'}
Dictionary
Methods
|
Method |
Description |
Example |
|
.keys() |
Returns all keys |
student.keys() → ['name','age','grade'] |
|
.values() |
Returns all values |
student.values() → ['John',22,'A'] |
|
.items() |
Returns key:value pairs |
student.items() → [('name','John'),('age',22)] |
|
.update({}) |
Update or add items |
student.update({"course":"CS"}) |
|
.pop(key) |
Removes item with key |
student.pop("grade") |
|
.clear() |
Removes all items |
student.clear() |
CODE:
student = {"name":
"John", "age": 22, "grade": "A"}
print(student.keys())
#
dict_keys(['name','age','grade'])
print(student.values())
#
dict_values(['John',22,'A'])
print(student.items())
#
dict_items([('name','John'),('age',22),('grade','A')])
student.update({"course":
"CS"})
print(student)
#
{'name':'John','age':22,'grade':'A','course':'CS'}
student.pop("grade")
print(student)
#
{'name':'John','age':22,'course':'CS'}
student.clear()
print(student)
# {}
OUTPUT:
dict_keys(['name', 'age',
'grade'])
dict_values(['John', 22,
'A'])
dict_items([('name',
'John'), ('age', 22), ('grade', 'A')])
{'name': 'John', 'age':
22, 'grade': 'A', 'course': 'CS'}
{'name': 'John', 'age':
22, 'course': 'CS'}
{}
del
Statement
Used to delete
a specific key
or the entire dictionary.
CODE:
student = {"name": "John", "age": 22, "course": "CS"} del student["age"] # Remove one keyprint(student) # {'name':'John','course':'CS'} del student # Delete whole dictionary# print(student) → ❌ Error (dictionary no longer exists)
OUTPUT
{'name': 'John',
'course': 'CS'}
A tuple in Python is an immutable ordered collection of elements.
- Tuples
are similar to lists, but unlike lists, they cannot be changed after their
creation (i.e., they are immutable).
- Tuples
can hold elements of different data types.
- The main
characteristics of tuples are
being ordered , heterogeneous and immutable.
What is
a Tuple?
- A tuple
is an ordered, immutable collection of elements.
- Similar
to lists, but cannot be changed (immutable) once created.
- Defined
using parentheses ().
Tuple Syntax in
Python:
1. Empty
Tuple
tuple1 = ()
2. Tuple with
Multiple Elements
tuple2 = (1, 2, 3, 4)
3. Tuple with
Mixed Data Types
tuple3 = (10,
"hello", 3.14, True)
4. Single
Element Tuple (must have a comma)
tuple4 = (5,) # Correct
tuple5 = (5) # ❌ Wrong → this is just an integer, not a tuple
tuple6 = (1, (2, 3), (4,
5))
6. Tuple using tuple() Constructor
tuple7 = tuple([1, 2,
3]) # from list
tuple8 =
tuple("ABC") # from
string
Output:
(1, 2, 3)
('A', 'B', 'C')
General Syntax:
tuple_name = (element1, element2, element3, ...)
CODE:
# creating tuples
tuple1 = (1, 2, 3)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (10, "hello", 3.5, True) # mixed data types
print(tuple1)
print(tuple2)
print(tuple3)
OUTPUT:
(1, 2, 3)
('apple', 'banana',
'cherry')
(10, 'hello', 3.5, True)
Creating
a Tuple
- A tuple
is created by placing all the items inside parentheses (), separated by
commas. A tuple can have any number of items and they can be of
different data
types.
CODE:
tup = ()
print(tup)
# Using String
tup = ('dear', 'students')
print(tup)
# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))
# Using Built-in Function
tup = tuple('students')
print(tup)
OUTPUT:
()
('dear', 'students')
(1, 2, 4, 5, 6)
('s', 't', 'u', 'd', 'e',
'n', 't', 's')
Creating a Tuple with Mixed Datatypes:
Tuples can
contain elements of various data types, including other tuples, lists, dictionaries and
even functions.
CODE:
tup = (5, 'Welcome', 7,
'class')
print(tup)
# Creating a Tuple with
nested tuples
tup1 = (0, 1, 2, 3)
tup2 = ('python', 'lab')
tup3 = (tup1, tup2)
print(tup3)
# Creating a Tuple with
repetition
tup1 = ('Hello students',) *
3
print(tup1)
# Creating a Tuple with
the use of loop
tup = ('hope u all good')
n = 5
for i in range(int(n)):
tup = (tup,)
print(tup)
OUTPUT:
(5, 'Welcome', 7,
'class')
((0, 1, 2, 3), ('python',
'lab'))
('Hello students', 'Hello
students', 'Hello students')
('hope u all good',)
(('hope u all good',),)
((('hope u all
good',),),)
(((('hope u ...
tuple()
in Python Function Examples
Create tuples
using tuple()
CODE:
tuple1 = tuple()
print("empty
tuple:", tuple1)
# when an iterable(e.g.,
list) is passed
list1= [ 1, 2, 3, 4 ]
tuple2 = tuple(list1)
print("list to
tuple:", tuple2)
# when an iterable(e.g.,
string) is passed
string = "Students from
CSE A & B";
tuple4 = tuple(string)
print("str to
tuple:", tuple4)
OUTPUT:
empty tuple: ()
list to tuple: (1, 2, 3,
4)
str to tuple: ('S', 't',
'u', 'd', 'e', 'n', 't', 's', ' ', 'f', 'r', 'o', 'm', ' ', 'C', 'S', 'E', ' ',
'A', ' ', '&', ' ', 'B')
Indexing
in Tuple
The index() method returns
the index of the specified element in the Tuple.
CODE:
vowels = ('a', 'e', 'i', 'o',
'u')
index = vowels.index('e')
OUTPUT:
1
The syntax of
the index() method is:
tuple.index(element,
start_index, end_index)
Here, the index() scans
the element in the tuple
from start_index to end_index.
The index() method can take
one to three parameters:
- element -
the item to scan
- start_index (optional)
- start scanning the element from the start_index
- end_index (optional)
- stop scanning the element at the end_index
index() Return Value:
The index() method returns:
- the
index of the given element in the tuple
- ValueError exception if the element is not found
in the tuple
CODE:
# tuple containing vowels
vowels = ('a', 'e', 'i', 'o',
'i', 'u')
index = vowels.index('e')
index = vowels.index('i')
OUTPUT:
Index of e: 1
Index of i: 2
In the above example, we have used
the index() method to find the index of a specified element in
the vowels tuple.
The element 'e' appears in
index 1 in the vowels tuple. Hence, the method
returns 1.
The element 'i' appears twice
in the vowels tuple. In this case, the index of the
first 'i' (which is 2) is returned.
CODE:
# tuple containing numbers
numbers = (0, 2, 4, 6, 8, 10)
index = numbers.index(3)
OUTPUT:
In the above example, we have used
the index() method to find the index of an element that is not
present in the numbers tuple.
Here, numbers doesn't contain
the number 3. Hence, it throws an exception
index() With Start and End Parameters:
alphabets = ('a', 'e', 'i',
'o', 'g', 'l', 'i', 'u')
index = alphabets.index('i')
# scans 'i' from index 4 to 7 and returns its index
index = alphabets.index('i',
4, 7)
print('Index of i in alphabets from index 4 to 7:', index)
OUPUT:
Index of i in alphabets
from index 4 to 7: 6
In the above example, we have used
the index() method to find the index of the
element 'i' with the start and end parameters.
Here, 'i' is scanned from
index 4 to index 7 in the tuple alphabets. Once found,
the index of the scanned 'i' is returned.
Tuple
Slicing
Tuple slicing is a
technique to extract a sub-part of a tuple. It uses a range of indices to
create a new tuple from the original tuple.
CODE:
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6,
7, 8, 9)
# Slice from index 2 to 5
s1 = tup[2:6]
print(s1)
# Slice from the beginning to
index 3
s2 = tup[:4]
print(s2)
# Slice from index 5 to the
end
s3 = tup[5:]
print(s3)
# Slice the entire tuple
s4 = tup[:]
print(s4)
OUTPUT:
(0, 1, 2, 3)
(5, 6, 7, 8, 9)
(0, 1, 2, 3, 4, 5, 6, 7,
8, 9)
The syntax for slicing is straightforward:
tuple[start:stop:step]
- start: The starting index from where the
slice begins (inclusive). Default is 0.
- stop: The ending index where the slice
ends (exclusive).
- step: The step size or stride. Default is
1
Using Negative Indices:
CODE:
Negative indices can be used to slice
tuples from the end.
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6,
7, 8, 9)
# Slice from the third last
to the end
s1 = tup[-3:]
print(s1)
# Slice from the beginning to
the third last
s2 = tup[:-3]
print(s2)
# Slice from the third last
to the second last
s3 = tup[-3:-1]
print(s3)
OUTPUT:
(0, 1, 2, 3, 4, 5, 6)
(7, 8)
Using Step in Slicing
The step
parameter allows us to define the increment between indices for the slice.
CODE:
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6,
7, 8, 9)
# Slice with a step of 2
s1 = tup[1:8:2]
print(s1)
# Slice with a negative step
(reverse the tuple)
s2 = tup[::-1]
print(s2)
OUTPUT:
(1, 3, 5, 7)
(9, 8, 7, 6, 5, 4, 3, 2,
1, 0)
Built-in
Functions for Tuples in Python
len():Returns the number of items in a tuple.
CODE:
t = (10, 20, 30, 40)
print(len(t))
OUTPUT:
4
max():Returns the
largest element in the tuple.
CODE:
t = (5, 10, 3, 8)
print(max(t))
OUTPUT:
10
min():Returns the
smallest element in the tuple.
CODE:
t = (5, 10, 3, 8)
print(min(t))
OUTPUT:
3
sum(): Returns the
sum of numeric values in the tuple.
t = (1, 2, 3, 4, 5)
print(sum(t))
OUTPUT:
15
sorted(): Returns a
new sorted list from tuple elements (tuple itself remains unchanged).
CODE:
t = (4, 1, 3, 2)
print(sorted(t))
OUTPUT:
[1, 2, 3, 4]
tuple(): Converts
other data types (like list, string) into a tuple.
list1 = [1, 2, 3]
print(tuple(list1)) # Output: (1,
2, 3)
print(tuple(s)) # Output:
('a', 'b', 'c')
any(): Returns True
if any element in the tuple is True.
CODE:
t = (0, False, 5, 0)
print(any(t))
OUTPUT:
True (because 5 is True)
all(): Returns True
if all elements are True.
CODE:
t = (1, True, 5)
print(all(t))
OUTPUT:
True
CODE:
t2 = (0, 1, 2)
print(all(t2))
OUTPUT:
False (because of 0)
enumerate():Returns index
and value pairs as an enumerate object.
t = ("apple",
"banana", "cherry")
for index, value in
enumerate(t):
print(index, value)
Output:
0 apple
1 banana
2 cherry
count() (Tuple Method, not global): Counts the
number of times a value appears.
CODE:
t = (1, 2, 2, 3, 2, 4)
print(t.count(2))
OUTPUT:
3
index() (Tuple Method):Returns the
first index of a value.
CODE:
t = (10, 20, 30, 20, 40)
print(t.index(20))
OUTPUT:
1
|
Function |
Purpose |
|
len() |
Number of
elements |
|
max() |
Largest
element |
|
min() |
Smallest
element |
|
sum() |
Sum of
numeric elements |
|
sorted() |
Sorted list
from tuple |
|
tuple() |
Convert
into tuple |
|
any() |
True if any
element is True |
|
all() |
True if all
elements are True |
|
enumerate() |
Returns
index & value pairs |
|
count() |
Count
occurrences |
|
index() |
Find index
of element |
Similarities between Python Tuples and
Lists
- Tuples and lists are both used to store
collections of data.
- Tuples and lists are both heterogeneous data
types, which mean that you can store any kind of data type.
- Tuples and lists are both ordered, which means
the order that you put the items in are kept.
- Tuples and lists are both sequential data types
so you can iterate over the items contained.
- Items of both tuples and lists can be accessed
by an integer index operator, provided in square brackets, [index].
Differences between Python Tuples and
Lists
- Tuples are immutable objects and lists are
mutable objects.
- Once defined, tuples have a fixed length and
lists have a dynamic length.
- Tuples use less memory and are faster to access
than to lists.
- Tuple syntax uses round brackets or
parenthesis, and list syntax uses square brackets
Python Tuple vs. List Code
Let’s further
understand how the differences in tuples and lists may affect our Python code
in terms of time and memory efficiency.
As lists are
mutable, Python needs to allocate an extra memory block in case there is a need
to extend the size of the list object after we create it. In contrast, as tuples
are immutable and of a fixed size, Python allocates only the minimum memory
block required for the data.
As a result,
tuples are more memory-efficient than lists.
Let’s check
this in the code block below:
CODE:
import sys
a_tuple = tuple()
a_list = [1,2,3,4,5]
a_tuple = (1,2,3,4,5)
print(sys.getsizeof(a_list))
print(sys.getsizeof(a_tuple))
OUTPUT:
104 (bytes for the list
object)
88 (bytes for the tuple
object)
As you can
see from the output of the above code snippet, the memory required for the
identical list and tuple objects is different.
When it comes
to the time efficiency, again tuples have a slight advantage over the lists
especially when we consider lookup value.
CODE:
import sys, platform
import time
b_list =
list(range(10000000))
end_time = time.time()
print("Instantiation
time for LIST:", end_time - start_time)
start_time = time.time()
b_tuple =
tuple(range(10000000))
end_time = time.time()
print("Instantiation
time for TUPLE:", end_time - start_time)
start_time = time.time()
for item in b_list:
aa = b_list[20000]
end_time = time.time()
print("Lookup time for
LIST: ", end_time - start_time)
start_time = time.time()
for item in b_tuple:
aa = b_tuple[20000]
end_time = time.time()
print("Lookup time for
TUPLE: ", end_time - start_time)
Output:
3.6.9
Instantiation time for
LIST: 0.4149961471557617
Instantiation time for
TUPLE: 0.4139530658721924
Lookup time for
LIST: 0.8162095546722412
Lookup time for TUPLE: 0.7768714427947998
Dictionaries and Tuples are different data structures, but they are closely related because of how data is stored and accessed in Python.
Dictionaries
use Tuples internally
- A dictionary stores key–value pairs.
- When you call .items() on a dictionary, it
returns a collection of tuples, where each tuple is (key, value).
CODE:
student = {"name":
"Kevin", "age": 21}
print(student.items())
OUTPUT:
dict_items([('name',
'Kevin'), ('age', 21)])
Tuples can be Dictionary Keys
- Dictionary keys must be immutable.
- Since tuples are immutable, they can be used as
keys (lists cannot).
CODE:
locations = {
(10, 20): "Point A",
(30, 40): "Point B"
}
print(locations[(10, 20)])
OUTPUT
Point A
Conversion Between Tuples and Dictionaries
·
Dictionary
→ Tuple
student = {"name": "Kevin", "age": 21}tuple_data = tuple(student.items())print(tuple_data)
OUTPUT:
(('name', 'Kevin'), ('age', 21))
·
Tuple
→ Dictionary
CODE:
tuple_data = (("name", "Kevin"), ("age", 21))dict_data = dict(tuple_data)print(dict_data)
OUTPUT:
{'name': 'Kevin', 'age': 21}
When looping
through .items(), each item is unpacked as a tuple:
CODE:
student = {"name":
"Kevin", "age": 21}
for key, value in
student.items():
print("Key:", key,
"Value:", value)
OUTPUT:
Key: name Value: Kevin
Key: age Value: 21
zip()
Function in Python
Syntax:
zip(iterable1, iterable2,
...)
- Takes two or more iterables.
- Returns an iterator of tuples.
- Stops when the shortest iterable is
exhausted.
Zipping Two Lists:
CODE:
names = ["Kevin",
"Nandan", "Ravi"]
ages = [25, 30, 28]
zipped = zip(names,
ages) # returns an iterator
print(list(zipped))
OUTPUT:
[('Kevin', 25),
('Nandan', 30), ('Ravi', 28)]
Converting to Dictionary
CODE:
keys = ["id",
"name", "age"]
values = [101,
"Kevin", 30]
my_dict = dict(zip(keys,
values))
print(my_dict)
OUTPUT:
{'id': 101, 'name':
'Kevin', 'age': 30}
Unzipping (Reverse zip)
CODE:
pairs = [("a", 1),
("b", 2), ("c", 3)]
keys, values = zip(*pairs)
print(keys)
print(values)
OUTPUT:
('a', 'b', 'c')
(1, 2, 3)
Here is a table that compares zip() with other Python functions:
|
Feature |
zip() |
enumerate() |
itertools.zip_longest() |
|
Purpose |
Combine
iterables |
Add index
to iterable |
Combine
with padding |
|
Stops at |
Shortest
sequence |
Single
iterable |
Longest
sequence |
|
Returns |
Tuples of
elements |
Index-value
pairs |
Padded
tuples |
Python Sets
A set is a
collection of unique data, meaning that elements within a set cannot be
duplicated.
For instance,
if we need to store information about student IDs, a set is suitable since
student IDs cannot have duplicates.
Python Set Elements:
·
In Python, we create sets by placing all the
elements inside curly braces {}, separated by commas.
·
A set can have any number of items and they may be
of different types (integer, float, tuple, string,
etc.). But a set cannot have mutable elements like lists,
sets or dictionaries as
its elements.
Let's see an example
CODE:
# create a set of integer
type
student_id = {112, 114, 116,
118, 115}
print('Student ID:',
student_id)
# create a set of string type
vowel_letters = {'a', 'e',
'i', 'o', 'u'}
print('Vowel Letters:',
vowel_letters)
# create a set of mixed data
types
mixed_set = {'Hello', 101,
-2, 'Bye'}
print('Set of mixed data
types:', mixed_set)
OUTPUT:
Student ID: {112, 114,
115, 116, 118}
Vowel Letters: {'i', 'a',
'o', 'u', 'e'}
Set of mixed data types:
{'Bye', 101, -2, 'Hello'}
In the above
example, we have created different types of sets by placing all the elements
inside the curly braces {}.
Create an Empty Set in Python
Creating an
empty set is a bit tricky. Empty curly braces {} will make an empty
dictionary in Python.
To make a set
without any elements, we use the set() function without any argument.
For example,
CODE:
# create an empty set
empty_set = set()
# create an empty dictionary
empty_dictionary = { }
# check data type of
empty_set
print('Data type of
empty_set:', type(empty_set))
# check data type of
dictionary_set
print('Data type of
empty_dictionary:', type(empty_dictionary))
OUTPUT:
Data type of empty_set:
<class 'set'>
Data type of
empty_dictionary: <class 'dict'>
Here,
- empty_set - an empty set created
using set()
- empty_dictionary - an empty dictionary
created using {}
Finally, we
have used the type() function to know which class empty_set and empty_dictionary belong
to.
Duplicate Items in a Set
Let's see
what will happen if we try to include duplicate items in a set.
CODE:
numbers = {2, 4, 6, 6, 2, 8}
print(numbers)
OUTPUT:
{8, 2, 4, 6}
Remove an Element from a Set
We use
the discard() method to remove the
specified element from a set.
For example,
CODE:
languages = {'Swift', 'Java',
'Python'}
print('Initial Set:',languages)
# remove 'Java' from a set
removedValue =
languages.discard('Java')
print('Set after remove():',
languages)
OUTPUT:
Initial Set: {'Java',
'Swift', 'Python'}
Set after remove():
{'Swift', 'Python'}
Built-in Functions with Set:
Here are some
of the popular built-in functions that allow us to perform different operations
on a set.
|
Function |
Description |
|
Returns True
if all elements of the set are true (or if the set is empty). |
|
|
Returns True
if any element of the set is true. If the set is empty, returns False. |
|
|
Returns an
enumerate object. It contains the index and value for all the items of the
set as a pair. |
|
|
Returns the
length (the number of items) in the set. |
|
|
Returns the
largest item in the set. |
|
|
Returns the
smallest item in the set. |
|
|
Returns a
new sorted list from elements in the set(does not sort the set itself). |
|
|
Returns the
sum of all elements in the set. |
Python Set Operations:
Python Set
provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.
Union of Two
Sets
The union of
two sets A and B includes all the elements of sets A and B.
Set Union in Python:
We use
the | operator or the union() method to perform the set
union operation.
For example,
CODE:
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
# perform union operation
using |
print('Union using |:', A |
B)
# perform union operation
using union()
print('Union using union():',
A.union(B))
OUTPUT:
Union using |: {0, 1, 2,
3, 4, 5}
Union using union(): {0,
1, 2, 3, 4, 5}
Note: A|B and union() is
equivalent to A ⋃ B set
operation.
Set Intersection:
The
intersection of two sets A and B include the common
elements between set A and B.
Set Intersection in Python:
In Python, we
use the & operator or the intersection() method
to perform the set intersection operation.
For example,
CODE:
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
# perform intersection
operation using &
print('Intersection using
&:', A & B)
# perform intersection
operation using intersection()
print('Intersection using
intersection():', A.intersection(B))
OUTPUT:
Intersection using &:
{1, 3}
Intersection using
intersection(): {1, 3}
Note: A&B and intersection() is
equivalent to A ⋂ B set
operation.
Difference between Two Sets
The difference
between two sets A and B include elements of set A that
are not present on set B.
We use
the - operator or the difference() method
to perform the difference between two sets.
For example
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference
operation using &
print('Difference using
&:', A - B)
# perform difference
operation using difference()
print('Difference using
difference():', A.difference(B))
OUTPUT:
Difference using &:
{3, 5}
Difference using
difference(): {3, 5}
Set Symmetric Difference:
The symmetric
difference between two sets A and B includes all elements
of A and B without the common elements.
Set Symmetric Difference in Python:
In Python, we use the ^ operator
or the symmetric_difference() method
to perform symmetric differences between two sets.
For example,
CODE:
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference
operation using &
print('using ^:', A ^ B)
# using
symmetric_difference()
print('using
symmetric_difference():', A.symmetric_difference(B))
OUTPUT:
using ^: {1, 3, 5, 6}
using
symmetric_difference(): {1, 3, 5, 6}
Set Methods
There are
many set methods, some of which we have already used above. Here is a list of
all the methods that are available with the set objects:
|
Method |
Description |
|
Adds an
element to the set |
|
|
Removes all
elements from the set |
|
|
Returns a
copy of the set |
|
|
Returns the
difference of two or more sets as a new set |
|
|
Removes all
elements of another set from this set |
|
|
Removes an
element from the set if it is a member. (Do nothing if the element is not in
set) |
|
|
Returns the
intersection of two sets as a new set |
|
|
Updates the
set with the intersection of itself and another |
|
|
Returns True
if two sets have a null intersection |
|
|
Returns True
if another set contains this set |
|
|
Returns True
if this set contains another set |
|
|
Removes and
returns an arbitrary set element. Raises KeyError if the set is empty |
|
|
Removes an
element from the set. If the element is not a member, raises a KeyError |
|
|
Returns the
symmetric difference of two sets as a new set |
|
|
Updates a
set with the symmetric difference of itself and another |
|
|
Returns the
union of sets in a new set |
|
|
Updates the
set with the union of itself and others |
CODE:
# Demonstration of Set
Methods in Python
# Initial sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
print("Initial
Sets:")
print("A =", A)
print("B =", B)
print("-" * 40)
# 1. add()
A.add(10)
print("After
add(10):", A)
# 2. clear()
temp = {1, 2, 3}
temp.clear()
print("After
clear():", temp)
# 3. copy()
C = A.copy()
print("Copy of A:",
C)
# 4. difference()
print("A - B
(difference):", A.difference(B))
# 5. difference_update()
A.difference_update(B)
print("After
A.difference_update(B):", A)
# Reset A for further
operations
A = {1, 2, 3, 4, 5}
# 6. discard()
A.discard(3)
print("After
discard(3):", A)
A.discard(100) # No error
print("After
discard(100):", A)
# 7. intersection()
print("A ∩ B
(intersection):", A.intersection(B))
# 8. intersection_update()
A.intersection_update(B)
print("After
A.intersection_update(B):", A)
# Reset A
A = {1, 2, 3, 4, 5}
# 9. isdisjoint()
print("A and {6,7} are
disjoint?:", A.isdisjoint({6,7}))
print("A and B are
disjoint?:", A.isdisjoint(B))
# 10. issubset()
print("{1,2} ⊆ A?:", {1,2}.issubset(A))
# 11. issuperset()
print("A ⊇ {1,2}?:", A.issuperset({1,2}))
# 12. pop()
popped = A.pop()
print("Popped
element:", popped)
print("After
pop():", A)
# 13. remove()
A.remove(2)
print("After
remove(2):", A)
# A.remove(100) # ❌ would raise KeyError
# 14. symmetric_difference()
print("A Δ B
(symmetric_difference):", A.symmetric_difference(B))
# 15.
symmetric_difference_update()
A.symmetric_difference_update(B)
print("After
A.symmetric_difference_update(B):", A)
# Reset A
A = {1, 2, 3, 4, 5}
# 16. union()
print("A ∪ B (union):", A.union(B))
# 17. update()
A.update(B)
print("After
A.update(B):", A)
OUTPUT:
Initial Sets:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7}
----------------------------------------
After add(10): {1, 2, 3,
4, 5, 10}
After clear(): set()
Copy of A: {1, 2, 3, 4,
5, 10}
A - B (difference): {10,
1, 2, 3}
After
A.difference_update(B): {1, 2, 3, 10}
After discard(3): {1, 2,
4, 5}
After discard(100): {1,
2, 4, 5}
A ∩ B (intersection): {4,
5}
After
A.intersection_update(B): {4, 5}
A and {6,7} are
disjoint?: True
A and B are disjoint?:
False
{1,2} ⊆ A?: True
A ⊇ {1,2}?: True
Popped element: 1
After pop(): {2, 3, 4, 5}
After remove(2): {3, 4,
5}
A Δ B (symmetric_difference):
{3, 6, 7}
After
A.symmetric_difference_update(B): {3, 6, 7}
A ∪ B (union): {1, 2, 3, 4, 5, 6, 7}
After A.update(B): {1, 2,
3, 4, 5, 6, 7}
Frozenset
A frozenset is an immutable version of
a set.
- It
stores unique, unordered elements like a set.
- But
once created, you cannot change it (no add, remove, update).
- Since
it’s immutable, it is hashable → can be used as a dictionary key or inside
another set.
Syntax
frozenset(iterable)
·
iterable → can be list, tuple, string, set, or any
iterable.
·
Returns a frozenset object.
Return value from frozenset():
The frozenset() function
returns an immutable frozenset initialized with elements from the
given iterable.
If no
parameters are passed, it returns an empty frozenset.
Working of Python frozenset()
CODE:
# tuple of vowels
vowels = ('a', 'e', 'i', 'o',
'u')
fSet = frozenset(vowels)
print('The frozen set is:',
fSet)
print('The empty frozen set
is:', frozenset())
# frozensets are immutable
fSet.add('v')
OUTPUT:
The frozen set is:
frozenset({'i', 'a', 'o', 'u', 'e'})
The empty frozen set is:
frozenset()
frozenset() for Dictionary:
When you use
a dictionary as an iterable for a frozen set, it only takes keys of the
dictionary to create the set.
CODE:
# random dictionary
person = {"name": "John",
"age": 23, "gender": "male"}
fSet = frozenset(person)
print('The frozen set is:',
fSet)
OUTPUT:
The frozen set is:
frozenset({'age', 'name', 'gender'})
Frozenset operations
Like normal
sets, frozenset can also perform different operations like copy(), difference(), intersection(), symmetric_difference(), and union().
CODE:
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy() # Output: frozenset({1, 2, 3, 4})
print(C)
# union
print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6})
# intersection
print(A.intersection(B)) # Output: frozenset({3, 4})
# difference
print(A.difference(B)) # Output: frozenset({1, 2})
# symmetric_difference
print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6})
OUTPUT:
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5,
6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})
CODE:
# Frozensets
# initialize A, B and C
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])
# isdisjoint() method
print(A.isdisjoint(C)) # Output: True
# issubset() method
print(C.issubset(B)) # Output: True
# issuperset() method
print(B.issuperset(C)) # Output: True
OUTPUT:
True
True
True
* WEEK III PROGRAMS *
1) 1) Write a program to
create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
CODE:
Method I: (Simple tuple
concatenation using +)
# Program to
create tuples and concatenate them
# Creating
tuples for two members
member1 = ("John", 21, "Hyderabad",
"OU")
member2 = ("Rohit", 22, "Delhi", "DU")
# Concatenating
the tuples
concatenated = member1 + member2
# Printing the
concatenated tuple
print("Concatenated Tuple:", concatenated)
OUTPUT:
Method II: (Using
tuple() and list conversion)
member1 = ("Richard", 21, "Hyderabad",
"OU")
member2 = ("Rohit", 22, "Delhi", "DU")
concatenated = tuple(list(member1) + list(member2))
print("Concatenated Tuple:", concatenated)
OUTPUT:
2)
2) Write a program to count the number of
vowels in a string (No control flow
allowed).
CODE:
Method I:( Using
count())
# Program to count vowels in
a string (no control flow)
s = "Education’s purpose is to replace an empty mind with an
open one"
vowels = "aeiouAEIOU"
# Count vowels by summing
occurrences of each vowel
count = sum(s.count(v) for v in vowels)
print("Number of vowels:", count)
OUTPUT:
Method II: (Using filter() and len())
# Program to count vowels in
a string (no control flow)
s = "Education’s purpose is to replace an empty mind with an
open one"
vowels = "aeiouAEIOU"
# Filter vowels and count
them
count = len(list(filter(lambda ch: ch in vowels, s)))
print("Number of vowels:", count)
OUTPUT:
3)
3) Write a program to
check if a given key exists in a dictionary or not.
CODE:
Method I (Using in
operator)
# Program
to check if a given key exists in a dictionary
my_dict = {"name": "Richard",
"age": 21, "college": "OU"}
key = "age"
if key in my_dict:
print(f"Key '{key}' exists in
the dictionary")
else:
print(f"Key '{key}' does not
exist in the dictionary")
OUTPUT:
Method II-( Using get() method)
# Program
to check if a given key exists in a dictionary
my_dict = {"name": "Alxa",
"age": 21, "college": "OU"}
key = "address"
if my_dict.get(key) is not None:
print(f"Key '{key}' exists in
the dictionary")
else:
print(f"Key '{key}' does not
exist in the dictionary")
OUTPUT:
4
4) Write a program to add a new key-value pair to an existing dictionary.
Code:
Method I: (Direct
Assignment)
# Program
to add a new key-value pair to a dictionary
my_dict = {"name": "kevin",
"age": 21}
# Adding
a new key-value pair
my_dict["college"] = "OU"
print("Updated Dictionary:", my_dict)
OUTPUT:
Method II: (Using
update() Method)
# Program
to add a new key-value pair to a dictionary
my_dict = {"name": "Richard",
"age": 22}
# Adding
a new key-value pair
my_dict.update({"college":
"DU"})
print("Updated Dictionary:", my_dict)
OUTPUT:
5) 5) Write a program to sum all the items in a given dictionary.
CODE:
Method I: (Using sum()
and values())
# Program
to sum all values in a dictionary
my_dict = {"a": 100, "b":
200, "c": 300}
total = sum(my_dict.values())
print("Sum of dictionary values:",
total)
OUTPUT:
Method II: (Using Loop)
# Program
to sum all values in a dictionary
my_dict = {"x": 100, "y":
200, "z": 300}
total = 0
for value in my_dict.values():
total += value
print("Sum of dictionary values:",
total)
OUTPUT:
No comments:
Post a Comment