Unit 4
Unit 4
Dictionaries are used to store data values in key: value pairs. A dictionary is a
collection which is ordered, changeable and do not allow duplicates.
Here, keys are unique identifiers that are associated with each value.
Creating a Dictionary:
EXAMPLE:
print(capital_city)
OUTPUT:
Here,
Dictionary can also be created by the built-in function dict(). An empty dictionary can
be created by just placing to curly braces {}.
EXAMPLE:
Dict = {}
Output: {}
Addition of elements can be done in multiple ways. One value at a time can be added
to a Dictionary by defining value along with the key
In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets.
EXAMPLE:
print(Dict['name'])
print(Dict[1])
Output:
Dictionary methods
clear() – Remove all the elements from the dictionary
copy() – Returns a copy of the dictionary
get() – Returns the value of specified key
items() – Returns a list containing a tuple for each key value pair
keys() – Returns a list containing dictionary’s keys
pop() – Remove the element with specified key
popitem() – Removes the last inserted key-value pair
update() – Updates dictionary with specified key-value pairs
values() – Returns a list of all the values of dictionary
EXAMPLE:
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
# copy() method
dict2 = dict1.copy()
print(dict2)
# clear() method
dict1.clear()
print(dict1)
# get() method
print(dict2.get(1))
# items() method
print(dict2.items())
# keys() method
print(dict2.keys())
# pop() method
dict2.pop(4)
print(dict2)
# popitem() method
dict2.popitem()
print(dict2)
# update() method
dict2.update({3: "Scala"})
print(dict2)
# values() method
print(dict2.values())
output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
Dictionary operations
1. Definition operations
These operations allow us to define or create a dictionary.
1.1.{ }
Creates an empty dictionary or a dictionary with some initial values.
y = {}
x = {1: "one", 2: "two", 3: "three"}
2. Mutable operations
These operations allow us to work with dictionaries, but altering or modifying their
previous definition.
2.1. [ ]
Adds a new pair of key and value to the dictionary, but in case that the key already
exists in the dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:
{'one': 1, 'two': 2}
y['two'] = 'dos'
print(y)
Output:
{'one': 1, 'two': 'dos'}
2.2. del
Del statement can be used to remove an entry (key-value pair) from a dictionary.
y = {'one': 1, 'two': 2}
print(y)
Output:
{'one': 1, 'two': 2}
del y['two']
print(y)
Output:
{'one': 1}
2.3. Update
This method updates a first dictionary with all the key-value pairs of a second
dictionary. Keys that are common to both dictionaries, the values from the second
dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)
print(x)
Output:
{'one': 1, 'two': 2, 'three': 3}
3. Immutable operations
These operations allow to work with dictionaries without altering or modifying their
previous definition.
3.1. len
Returns the number of entries (key-value pairs) in a dictionary.
x = {'one': 0, 'two': 2}
print(len(x))
Output:2
3.2. Keys
This method allows you to get all the keys in the dictionary. It is often used in a “for
loop” to iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:dict_keys(['one', 'two'])
3.3. Values
This method allows you to obtain all the values stored in a dictionary.
x = {'one': 1, 'two': 2}
print(x.values())
Output:dict_values([1, 2])
3.4. Items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
Output:dict_items([('one', 1), ('two', 2)])
3.5. in
Attempting to access a key that is not in a dictionary will raise an exception. To
handle this exception, the in method is used to test whether a key exists in a
dictionary, returns True if a dictionary has a value stored under the given key and
False otherwise.
y = {'one': 1, 'two': 2}
del y['three']
Output: KeyError: 'three'y = {'one': 1, 'two': 2}if 'three' in y:
del y['three']
print(y)Output:{'one': 1, 'two': 2}
3.6. Get
Returns the value associated with a key if the dictionary contains that key, in case that
the dictionary does not contain the key, you can specified a second optional argument
to return a default value, if the argument is not included get method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
print(y.get('three', 'The key does not exist.'))
Output:
1
None
The key does not exist.
LISTS
A list in Python is used to store the sequence of various types of data. A list can
be defined as a collection of values or items of different types.
Python lists are mutable type which implies that we may modify its element
after it has been formed.
The items in the list are separated with the comma (,) and enclosed with the
square brackets [].
Characteristics of Lists
Example:
A list can have any number of items and they may be of different types (integer, float,
string, etc.). For example,
# empty list
my_list = []
In Python, each item in a list is associated with a number. The number is known
as a list index. The elements of the list can be accessed by using the slice
operator [].
The index starts from 0 and goes to length - 1. The first element of the list is
stored at the 0th index, the second element of the list is stored at the 1st index,
and so on.
Python allows negative indexing for its sequences. The index of -1 refers to the
last item, -2 to the second last item and so on.
The sub-list of the list can be get using the following syntax.
list_varible[start:stop:step]
Example:
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
print(list[:])
print(list[2:5])
print(list[-1])
OUTPUT:
1
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
7
Method Description
Code
l =[]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
l.append(input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
l.remove(1)
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:3
Enter the item:32
Enter the item:56
Enter the item:81
printing the list items..
32 56 81
printing the list items..
32 81
Python List Operations
. The different operations of list are
Repetition
Concatenation
Length
Iteration
Membership
1. Repetition
The repetition operator enables the list elements to be repeated multiple times.
Code
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length
It is used to get the length of the list
Code:
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
len(list1)
Output:
9
4. Iteration
The for loop is used to iterate over the list elements.
Code
list1 = [12, 14, 16, 39, 40]
for i in list1:
print(i)
Output:
12
14
16
39
40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
list1 = [100, 200, 300, 400, 500]
print(600 in list1)
print(300 in list1)
print(100 in list1)
Output:
False
True
True
or
A tuple is a collection of objects which ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
1Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated
by commas.
A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).
Example:
# Empty tuple
my_tuple = ()
print(my_tuple)
my_tuple = (1, 2, 3)
print(my_tuple)
print(my_tuple)
# nested tuple
print(my_tuple)
Output
()
(1, 2, 3)
Each element of a tuple is represented by index numbers (0, 1, ...) where the first
element is at index 0.
The index operator [] is used to access an item in a tuple, where the index starts from
0.
Example:
letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")
print(letters[0])
print(letters[5])
Output:
prints "p"
prints "a"
2.Slicing
We can access a range of items in a tuple by using the slicing operator colon:.
For example:
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[1:4])
print(my_tuple[7:])
print(my_tuple[:])
output:
Prints ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations used on strings .
The most common is the index() method, which can be used to find the position of a
given element in the tuple:
The method count (), which returns the number of times a given element appears in
the tuple:
Example:
print(my_tuple.index('l'))
output:
cmp(tuple1, tuple2)
1 Compares elements of both tuples.
len(tuple)
2 Gives the total length of the tuple.
max(tuple)
3 Returns item from the tuple with max value.
min(tuple)
4 Returns item from the tuple with min value.
tuple(seq)
5 Converts a list into tuple.
Python Set
A Python set is the collection of the unordered items. Each element in the set
must be unique, immutable, and the sets remove the duplicate elements. Sets are
mutable which means we can modify it after its creation.
(Or)
Sets are used to store multiple items in a single variable. A set is a collection
which is unordered, unchangeable (but the items can be removed and add new items)
and unindexed. Sets are written with curly brackets {}.
Example
thisset = {"apple", "banana", "cherry"}
print(thisset)
print(type(thisset))
Output: {'banana', 'apple', 'cherry'}
<class 'set'>
Methods in SET:
Python provides the add() method and update() method which can be used to
add some particular item to the set.
The add() method is used to add a single element whereas the update() method
is used to add multiple elements to the set.
The discard() method and remove() method is used to remove the specified
element from a set.
The difference between these function, using discard() function if the item does
not exist in the set then the set remain unchanged whereas remove() method
will through an error.
The del keyword will delete the set completely.
The pop() method is used to remove a random item.
Example:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
thisset.remove("banana")
print(thisset)
thisset.clear()
print(thisset)
Output:
{'orange', 'cherry', 'apple', 'banana'}
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}
{'apple', 'mango', 'cherry', 'pineapple', 'papaya'}
set()
Function Description
Python Set provides different built-in methods to perform mathematical set operations
like union, intersection, subtraction, and symmetric difference.
The union of two sets A and B include all the elements of set A and B. The | operator
or the union() method is used to perform the set union operation. For example,
# 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}
Set Intersection
The intersection of two sets A and B include the common elements between set A and
B.The & operator or the intersection() method is used to perform the set intersection
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. The - operator or the difference() method is used to perform the
difference between two sets.
Set Symmetric Difference
The symmetric difference between two sets A and B includes all elements of A and B
without the common elements. The ^ operator or the symmetric_difference() method
is used to perform symmetric difference between two sets.
Example:
A = {2, 3, 5}
# second set
B = {1, 2, 6}
# perform difference operation using &
print('using ^:', A ^ B)
Output:
using ^: {1, 3, 5, 6}
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.
In python, a derived class can inherit base class by just mentioning the base in
the bracket after the derived class name. Consider the following syntax to inherit a
base class into the derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the
bracket.
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
The issubclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class, and
false otherwise.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:
True
False
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects
and classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.
Encapsulation:
Encapsulation is one of the most fundamental concepts in object-oriented
programming (OOP). This is the concept of wrapping data and methods that work
with data in one unit. This prevents data modification accidentally by limiting access
to variables and methods. Encapsulation is demonstrated by a class which
encapsulates all data, such as member functions, variables, and so forth.
EXAMPLE:
class Employee:
def __init__(self, name, salary, project):
# data members
self.name = name
self.salary = salary
self.project = project
# method
def show(self):
print("Name: ", self.name, 'Salary:', self.salary)
# method
def work(self):
print(self.name, 'is working on', self.project)
# creating object of a class
emp = Employee('Jessa', 8000, 'NLP')
# calling public method of the class
emp.show()
emp.work()
Output:
Name: Jessa Salary: 8000
Jessa is working on NLP
Encapsulation allows us to restrict accessing variables and methods directly and
prevent accidental data modification by creating private data members and methods
within a class. Encapsulation is a way to can restrict access to methods and variables
from outside of class.
Encapsulation can be achieved by declaring the data members and methods of a
class either as private or protected.
Access modifiers limit access to the variables and methods of a class. Python
provides three types of access modifiers private, public, and protected. But in Python,
we don’t have direct access modifiers like public, private, and protected. It can
achieved this by using single underscore and double underscores.
Example:
class Employee:
# constructor
def __init__(self, name, salary):
# public data member
self.name = name
# private member
self.__salary = salary
Polymorphism
That is, the same entity (method or operator or object) can perform different
operations in different scenarios
Example:
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")
class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")
class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")