Defining a Dictionary
Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair
maps the key to its associated value.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly
braces ({}). A colon (:) separates each key from its associated value:
d={
<key>: <value>,
<key>: <value>,
<key>: <value>
You can also construct a dictionary with the built-in dict() function. The argument to dict()
should be a sequence of key-value pairs. A list of tuples works well for this:
d = dict([
(<key>, <value>),
(<key>, <value),
(<key>, <value>)
])
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
print(country_capitals["United States"]) # Washington D.C.
print(country_capitals["England"]) # London
Change Dictionary Items
Python dictionaries are mutable (changeable). We can change the value of a dictionary element
by referring to its key. For example,
country_capitals = {
"United States": "Washington D.C.,
"Italy": "Naples",
"England": "London"
# change the value of "Italy" key to "Rome"
country_capitals["Italy"] = "Rome"
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'England': 'London'}
Add Items to a Dictionary
We can add an item to the dictionary by assigning a value to a new key (that does not exist in the
dictionary). For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
# add an item with "Germany" as key and "Berlin" as its value
country_capitals["Germany"] = "Berlin"
print(country_capitals)
Output
{'United States': 'Washington D.C.', 'Italy': 'Rome', 'Germany': 'Berlin'}
Note: We can also use the update method() to add or change dictionary items.
Remove Dictionary Items
We use the del statement to remove an element from the dictionary. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
# delete item having "United States" key
del country_capitals["United States"]
print(country_capitals)
If we need to remove all items from the dictionary at once, we can use the clear() method.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
country_capitals.clear()
print(country_capitals) # {}
Python Dictionary Methods
Here are some of the commonly used dictionary methods.
Function Description
pop() Remove the item with the specified key.
update() Add or change dictionary items.
clear() Remove all the items from the dictionary.
keys() Returns all the dictionary's keys.
values() Returns all the dictionary's values.
get() Returns the value of the specified key.
We can check whether a key exists in a dictionary using the in operator.
my_list = {1: "Hello", "Hi": 25, "Howdy": 100}
print(1 in my_list) # True
# the not in operator checks whether key doesn't exist
print("Howdy" not in my_list) # False
print("Hello" in my_list) # False
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
Iterating Through a Dictionary
A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary
maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
# print dictionary keys one by one
for country in country_capitals:
print(country)
print("----------")
# print dictionary values one by one
for country in country_capitals:
capital = country_capitals[country]
print(capital)
set
A set is a collection of unique data. That is, elements of a set cannot be duplicate. For example,
Suppose we want to store information about student IDs. Since student IDs cannot be duplicate,
we can use a set.
In Python, we create sets by placing all the elements inside curly braces {}, separated by comma.
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,
# 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)
Immutable set
Python Method creates an immutable Set object from an iterable. It is a built-in Python function.
As it is a set object, therefore, we cannot have duplicate values in the frozenset.
animals = frozenset(["cat", "dog", "lion"])
print("cat" in animals)
print("elephant" in animals)
Syntax : frozenset(iterable_object_name)
Duplicate Items in a Set
Let's see what will happen if we try to include duplicate items in a set.
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
Add and Update Set Items in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it.
Add Items to a Set in Python
In Python, we use the add() method to add an item to a set. For example,
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
# using add() method
numbers.add(32)
print('Updated Set:', numbers)
Output
Initial Set: {34, 12, 21, 54}
Updated Set: {32, 34, 12, 21, 54}
In the above example, we have created a set named numbers. Notice the line,
numbers.add(32)
Here, add() adds 32 to our set.
Update Python Set
The update() method is used to update the set with items other collection types (lists, tuples, sets,
etc). For example,
companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
companies.update(tech_companies)
print(companies)
# Output: {'google', 'apple', 'Lacoste', 'Ralph Lauren'}
Here, all the unique elements of tech_companies are added to the companies set.
Remove an Element from a Set
We use the discard() method to remove the specified element from a set. For example,
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: {'Python', 'Swift', 'Java'}
Set after remove(): {'Python', 'Swift'}
Here, we have used the discard() method to remove 'Java' from the languages set.
Iterate Over a Set in Python
fruits = {"Apple", "Peach", "Mango"}
# for loop to access each fruits
for fruit in fruits:
print(fruit)
Output
Mango
Peach
Apple
Find Number of Set Elements
We can use the len() method to find the number of elements present in a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)
# find number of elements
print('Total Elements:', len(even_numbers))
Output
Set: {8, 2, 4, 6}
Total Elements: 4
Here, we have used the len() method to find the number of elements present in a Set.
Python Set Operations
Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, difference, and symmetric difference.
Union of Two Sets
The union of two sets A and B include all the elements of set A and B.
We use the | operator or the union() method 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}
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.
In Python, we use the & operator or the intersection() method to perform the set intersection
operation. For example,
# 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}
Note: A - B and A.difference(B) is equivalent to A - B set operation.
Set Symmetric Difference
The symmetric difference between two sets A and B includes all elements of A and B without the
common elements.
In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric
difference between two sets. For example,
# 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}
Check if two sets are equal
We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
# perform difference operation using &
if A == B:
print('Set A and Set B are equal')
else:
print('Set A and Set B are not equal')
Output
Set A and Set B are equal
In the above example, A and B have the same elements, so the condition
if A == B
evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is executed.
Other Python 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
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
discard() Removes an element from the set if it is a member. (Do nothing if the
element is not in set)
intersection() Returns the intersection of two sets as a new set
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is
empty
remove() Removes an element from the set. If the element is not a member, raises
a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others
Object Oriented programming
Object-oriented programming (OOP) is a programming paradigm that provides a means of
structuring programs so that properties and behaviors are bundled into individual objects.
In Python, almost everything is an object, with its properties and methods. A Class is like an
object blueprint, from which objects can be created. Objects can inherit properties and methods
from other objects, and they can also be extended to add new properties and methods.
OOP in Python is based on the following concepts:
Classes: Classes are blueprints for creating objects. They define the properties and methods that
objects will have.
Objects: Objects are instances of classes. They have the properties and methods defined by their
class.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
he __init__() Function
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a
string.
If the __str__() function is not set, the string representation of the object is returned:
Example
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
Inheritance
Inheritance is a feature of object-oriented programming that allows you to create a new class that
inherits from an existing class. The new class, called the subclass, inherits all of the properties
and methods of the existing class, called the base class.
Inheritance in Python is implemented using the class keyword. To create a subclass, you simply
specify the base class in the parentheses after the class name.
For example, the following code creates a subclass called Dog that inherits from the Animal
class:
class Animal:
def eat(self):
print("I'm eating!")
class Dog(Animal):
def bark(self):
print("Woof!")
The Dog class inherits all of the methods of the Animal class, including eat(). It also has its own
method, bark().
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.
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.
Python Inheritance
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
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
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level
inheritance is archived when a derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi-level inheritance is archived in python.
The syntax of multi-level inheritance is given below.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
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(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Encapsulation
Encapsulation is one of the critical features of object-oriented programming, which involves the
bundling of data members and functions inside a single class. Bundling similar data members
and functions inside a class also helps in data hiding. Encapsulation also ensures that objects are
self-sufficient functioning pieces and can work independently.
Why do we need Encapsulation in Python?
The advantages of Encapsulation in Python can be summed up as follows –
1. Encapsulation provides well-defined, readable code
The primary advantage of using Encapsulation in Python is that as a user, we do not need to
know the architecture of the methods and the data and can just focus on making use of these
functional, encapsulated units for our applications. This results in a more organized and clean
code. The user experience also improves greatly and makes it easier to understand applications as
a whole.
2. Prevents Accidental Modification or Deletion
Another advantage of encapsulation is that it prevents the accidental modification of the data and
methods. Let’s consider the example of NumPy again, if I had access to edit the library, then I
might make a mistake in the implementation of the mean function and then because of that
mistake, thousands of projects using NumPy would become inaccurate.
3. Encapsulation provides security
Encapsulation in Python is achieved through the access modifiers. These access modifiers ensure
that access conditions are not breached and thus provide a great user experience in terms of
security.
4. Encapsulation provides reusability
It is easier to reuse code when it is encapsulated. Creating objects that contain common
functionality allows us to reuse them in many settings.
Access Modifiers in Python encapsulation
Sometimes there might be a need to restrict or limit access to certain variables or functions while
programming. That is where access modifiers come into the picture.
Now when we are talking about access, 3 kinds of access specifiers can be used while
performing Encapsulation in Python. They are as follows :
Public Members
Private Members
Protected Members
Encapsulation in Python using public members
As the name suggests, the public modifier allows variables and functions to be accessible from
anywhere within the class and from any part of the program. All member variables have the
access modifier as public by default.
Now let’s check out how we can implement Encapsulation in Python using public methods –
# illustrating public members & public access modifier
class pub_mod:
# constructor
def __init__(self, name, age):
self.name = name;
self.age = age;
def Age(self):
# accessing public data member
print("Age: ", self.age)
# creating object
obj = pub_mod("Jason", 35);
# accessing public data member
print("Name: ", obj.name)
# calling public member function of the class
obj.Age()
Evidently, from the above code, you can make out that we declared two variables and two
methods of the class pub_mod. We were able to access the variables and methods wherever we
wanted with ease as the access modifier for them was public, which means they should be
accessible everywhere.
This claim is satisfied as we can see in the output –
Name: Jason
Age: 35
Encapsulation in Python using private members
The private access modifier allows member methods and variables to be accessed only within the
class. To specify a private access modifier for a member, we make use of the double underscore
__.
Let’s check out this example to understand how we can implement Encapsulation using private
members –
# illustrating private members & private access modifier
class Rectangle:
__length = 0 #private variable
__breadth = 0#private variable
def __init__(self):
#constructor
self.__length = 5
self.__breadth = 3
#printing values of the private variable within the class
print(self.__length)
print(self.__breadth)
rect = Rectangle() #object created
#printing values of the private variable outside the class
print(rect.length)
print(rect.breadth)
We have accessed len both within and outside the class in the above snippet. Let’s see what kind
of output that gives us.
Output –
Encapsulation in Python using protected members
What sets protected members apart from private members is that they allow the members to be
accessed within the class and allow them to be accessed by the sub-classes involved. In Python,
we demonstrate a protected member by prefixing with an underscore _ before its name.
As we know, if the members have a protected access specifier, it can also be referenced then
within the class and the subsequent sub-clas
So now let’s see this concept in action –
# illustrating protected members & protected access modifier
class details:
_name="Jason"
_age=35
_job="Developer"
class pro_mod(details):
def __init__(self):
print(self._name)
print(self._age)
print(self._job)
# creating object of the class
obj = pro_mod()
# direct access of protected member
print("Name:",obj.name)
print("Age:",obj.age)
Output –
Jason
35
Developer
It is quite clear from the output that the class pro_mod was successfully able to inherit the
variables from the class details and print them to the console, although they were protected
variables. And when we tried to refer to them outside of their parent class and the sub-class, we
got an AttributeError for the same.
Polymorphism
Polymorphism means multiple forms. In python we can find the same operator or function taking
multiple forms. It also useful in creating different classes which will have class methods with
same name. That helps in re using a lot of code and decreases code complexity. Polymorphism is
also linked to inheritance as we will see in some examples below.
Polymorphism in operators
The + operator can take two inputs and give us the result depending on what the inputs are. In the
below examples we can see how the integer inputs yield an integer and if one of the input is float
then the result becomes a float. Also for strings, they simply get concatenated. This happens
automatically because of the way the + operator is created in python.
Example
a = 23
b = 11
c = 9.5
s1 = "Hello"
s2 = "There!"
print(a + b)
print(type(a + b))
print(b + c)
print(type (b + c))
print(s1 + s2)
print(type(s1 + s2))
Running the above code gives us the following result −
Output
34
20.5
HelloThere!
Polymorphism in in-built functions
We can also see that different python functions can take inputs of different types and then
process them differently. When we supply a string value to len() it counts every letter in it. But if
we five tuple or a dictionary as an input, it processes them differently.
Example
str = 'Hi There !'
tup = ('Mon','Tue','wed','Thu','Fri')
lst = ['Jan','Feb','Mar','Apr']
dict = {'1D':'Line','2D':'Triangle','3D':'Sphere'}
print(len(str))
print(len(tup))
print(len(lst))
print(len(dict))
Running the above code gives us the following result −
Output
10
Polymorphism in user-defined methods
We can create methods with same name but wrapped under different class names. So we can
keep calling the same method with different class name pre-fixed to get different result. In the
below example we have two classes, rectangle and circle to get their perimeter and area using
same methods.
Example
from math import pi
class Rectangle:
def __init__(self, length, breadth):
self.l = length
self.b = breadth
def perimeter(self):
return 2*(self.l + self.b)
def area(self):
return self.l * self.b
class Circle:
def __init__(self, radius):
self.r = radius
def perimeter(self):
return 2 * pi * self.r
def area(self):
return pi * self.r ** 2
# Initialize the classes
rec = Rectangle(5,3)
cr = Circle(4)
print("Perimter of rectangel: ",rec.perimeter())
print("Area of rectangel: ",rec.area())
print("Perimter of Circle: ",cr.perimeter())
print("Area of Circle: ",cr.area())
Running the above code gives us the following result −
Output
Perimter of rectangel: 16
Area of rectangel: 15
Perimter of Circle: 25.132741228718345
Area of Circle: 50.26548245743669