Thursday, March 11, 2021

Introduction to OOPS using Python - ( important points to remember )

 


Introduction to OOPS using Python

 

* OOPS is one of the most revolutionary concepts in Computer Science , and its full form is called as Object Oriented Programming System ( OOPS ) which is based on languages like Smalltalk , Simula-67 , C++ , Java , Python etc .

 

* The languages like C , Pascal , Fortran etc are called as Procedure Oriented Programming which perform a given set of tasks .

 

* While developing software , the main task is divided into several sub tasks and each of the sub task can be represented as a procedure or a function .

 

* The main task is therefore composed of several procedures and functions and the approach for this is called as Procedure Oriented Approach .

 

* Procedure Oriented Approach for OOPS based programs . Languages like C++ , Java and Python use classes and Objects in their programs and are called as + , Java and Python use classes and Objects in their programs and are called as Object Oriented Programming Languages .

 

* A Class is a module which itself contains data and methods (functions) to achieve the task.

 

* The main task is divided into several sub tasks and they are represented as classes. Each class can perform several inter-related tasks for which several methods are written in a class . This approach is called as Object Oriented Approach .

 

* Programmers follow a Procedure Oriented Approach for looking into problems that associate with problems related to Procedure Oriented Programming .

 

Important Points to Remember : Dictionary Objects in Python ( syntax , usage , methods , behaviour etc )

 

  Points to Remember: Dictionary Objects in Python




 

1) A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary object , the first element is considered as the 'key' and the immediate next element is considered as its associated 'value' .

 

2) The Key and Value Pairs should be written inside a dictionary by separating them with the help of a colon (:) operator. Each pair should be separated with the help of a comma sign. All the key-value pairs of the dictionary should be written inside curly braces { }

 

3) Indexing and Slicing are not useful to access the elements of a dictionary

 

4) While inserting a new element or modifying the existing element, it is preferable to use the given format:

 

dict(key) = Value

 

5) The keys of a dictionary should be unique and must be Immutable which means that once the data for the Keys is assigned, one cannot change the data type of the elements inside the dictionary.

 

6) The keys of a dictionary should be unique and belong to immutable datatype . The value associated with the key should be unique and should be immutable in nature.

 

7) The get(k,v) method returns the value upon taking the key 'k' . If the key is not found in the dictionary , then it will return a default value 'v'

 

8) The update({k:v}) method stores the key 'k' and its value 'v' pair into an existing dictionary

 

9) The dict() method converts a list or tuple or a zip object into a dictionary

 

10) The zip() method is useful to convert the sequences like lists into a zip class object

 

11) An ordered dictionary is a dictionary but it will keep the order of the elements

 

12) Ordered Dictionaries are created using the OrderedDict() method of collections module .

 

A descriptive article on - What are Ordered Dictionary Objects in Python and how to create them ( code over Jupyter Notebook IDE )

 



Ordered Dictionaries in Python


 

* The elements of a dictionary are not ordered . It means that the elements are not stored in the same order as they were entered into a dictionary

 

* For example , one can consider an employee database in a company which stores the employee details depending upon their seniority that is senior most employee's data may be inserted in the beginning of the database

 

* If the employee's details are stored in a dictionary , then the database will not show the employee details in the same order

 

* When the employee's details are changed , the seniority is disturbed and the data of the employee who joined the company first may not appear in the beginning of the dictionary .

 

* In such a case , the solution is to use ordered dictionaries .

 

* An Ordered Dictionary is a dictionary but it will keep the order of the elements in it . The elements are stored and maintained in the same order as they were entered into the ordered dictionary .

 

* One can create an ordered dictionary using the OrderedDict() method of the collections module . Therefore , we should import the method from the collections module as provided :

 

from collections import OrderedDict

 

Once the ordered dictionary item is created , one can assign an ordered dictionary with the name 'd' as given in the case :

 

d = OrderedDict()

 

One can store the key and values into the ordered dictionary 'd' as in the given manner :

 

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

 

Here , 10 is the identifier "Key" and its associated value is "A" . Therefore , the order is not disturbed as 'd' is the ordered dictionary . When we display the key-value pairs from the dictionary 'd' , we can see the same order .

 

=========================================

      Python Program to create a dictionary that

        does not change the order of Elements

=========================================

# create an ordered dictionary from

# collections import OrderedDict

 

d = OrderedDict()

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

# display the ordered Dictionary

for i , j in d.items():

    print(i,j)

 

Output

10 - A

11 - B

12 - C

13 - D




 

Python program to pass Dictionary Objects into Functions ( with sample code and pictorial representation of implementation in Jupyter Notebook )

 




Python Program to Convert Strings into Dictionary Object ( with sample code )

 


Wednesday, March 10, 2021

Converting Lists into Dictionary in Python ( sample code )

 

Converting Lists into Dictionary




 

* When we have two lists , it is possible to convert the lists into a dictionary

 

* For example , we have two lists containing the names of the countries and names of their capital cities

 

countries = [ "USA" , "India" , "Russia","China","Germany" ]

 

cities=["Washington","Delhi","Moscow","Beijing","Berlin"]

 

* If the user wants to create a dictionary out of these two lists by taking the elements of 'countries' list as keys and 'cities' list as values , then the dictionary would look like this :

 

d = { "USA":"Washington" , "India":"Delhi" ,

"Russia":"Moscow","China":"Beijing","Germany":"Berlin"}

 

* There are two steps involved to convert the lists into a dictionary

 

Step - 01 :

Create a "ZIP" class object by passing the two lists to the zip() function as :

 

z = zip(countries,cities)

 

The zip() function is useful to convert the sequences into a zip class object . There may be 1 or more sequences that can be passed to the zip() function . Therefore , we passed only 2 lists to the zip() function in the above statement . The resultant zip object is 'z' .

 

Step - 02 :

The second step is to convert the zip object into a dictionary by using the dict() function .

 

d = dict(z)

 

Here , the 0th element of the z object is taken as the 'key' and 1st element is converted into the 'value' . On a similar note , 2nd element is taken as the 'key' and '3rd' element is considered as the 'value' . All the values are stored in the dictionary object 'd' . If the user wants to display 'd' object , then the user can do this by using the following dictionary :

 

d = { "USA":"Washington" , "India":"Delhi" , "Russia":"Moscow" , "China":"Beijing", "Germany":"Berlin" }

 

Using FOR loop with Dictionaries in Python - sample example

 

Using FOR loop with Dictionaries


* FOR loop is very convenient to retrieve the elements of a dictionary .One can consider a simple dictionary that contains color code in smallcase and the corresponding color combination in the following manner and its name as the following :

 

colors = { "r":"Red" , "g":"Green" , "b":"Blue" , "w":"White"}

 

Here , 'r','g','w' characters represent the keys and "Red","Green","White" indicate the values represented by the Keys  Suppose one wants to retrieve only keys from "colors" dictionary , then one can use a for loop in the following manner :

 

for k in colors:

    print(k)

 

In the above loop , one can find that the iterator variable 'k' stores each element of the colors dictionary . Here the iterator , 'k' assumes only the keys and hence the loop displays only keys . Suppose , one wants to retrieve values associated from the keys , then one can obtain them by passing the key to the colors dictionary in the form of colors(k) . The following for loop retrieves all the color values from the colors dictionary .

 

for k in colors:

    print(colors[k])

 

Since these values are associated with keys , one can retrieve them only when we mention the keys . And suppose, one wants to retrieve both the keys and their corresponding values , then one can use the items method within the for loop in the given manner :

 

for k , v in colors.items():

    print(' Key = { } Value = { } '.format(k,v))

 

In the preceding code , the colors.items() method returns an object by the name of 'dict_items' that contains key and value pairs . Each of the value pairs is stored in "k" .

  

==========================================================

Python program to show the usage of for loop to retrieve the elements of dictionaries

# One can use a for loop with dictionaries in the following manner

colors = { 'r' : "Red" ,'g' : 'Green' , 'b':'Blue' , 'w':'white'}

# display only keys

for k in colors:

    print(k)

# pass keys to the dictionary and display the values

for k in colors:

    print(colors[k])

# items method returns the key and value pair into k,v

for k,v in colors.items():

    print('Key={ } Value={ }'.format(k,v))

 

Output

b

wr

g

Blue

White

Red

Green

Key=b Value=Blue

Key=w Value=White

Key=r Value=Red

Key=g Value=Green

 

In the similar manner , another program can be written to count the number of times each letter has occurred in a string .

For example , if "Book" is a string and one is supposed to find the number of occurrences of each letter in the string , then it means that the letter "B" has occurred for 1 time , and the letter "o" has occurred for 2 times and the letter 'k' occurred for 1 time .

In this program , one can use the "get()" method very effectively . Therefore , please recollect that the get() method is used on a dictionary object item to retrieve the value by giving the key .

If the key is not found within the dictionary , then it returns some default value .

The format of the get() method is as follows :

dict.get(x,0)

This statement says that if the key 'x' is found in the dictionary 'dict' , then one must return the 'value' from the dictionary else it would return 0 as result .

One can consider the following code in order to follow or understand the manner in which the combination of key and value for a given string sequence could be mapped to a dictionary and then it could be fetched back from the code :

 

dict = { }

str = "Book"

for x in str:

    dict[x] = dict.get(x,0) + 1

 

In the given code , the last statement should be considerd once again for better understanding and clarity .

 

dict[x] = dict.get(x,0) + 1

 

If one observes the right hand expression with "get()" method then one can observe that it says if 'x' is found in the dictonary 'dict' then it should return a value otherwise it should return a 0 . As we added a '1' to the value returned by the "get()" method and therefore , if 'x' is not found , then it returns a value of 1 .

 

But if 'x' is found , then it returns the value of 'x' plus 1 . One can observe the left side expression , that is dict[x] . Here , this represents 'x' is stored as key in the dictionary . Therefore , whatever the value is returned by the right side expression , the value would be stored into that dictionary as value

for the key 'x' . This means that :

 

dict[x] = value returned by get() + 1

Let's consider the first letter of the string that is "B" . Since the dictionary is initially empty , there are no elements within the dictionary and therefore 'B' is not found within the dictionary .

 

Therefore , dict.get(x,0) + 1 returns the value 1 . In the left side , we have dict[x] which represents dict['B'] . Here , 'B' is taken as the key . And hence the statement becomes :

 

dict['B'] = 1

 

This means 'B' is stored as a key and the value 1 is stored as a value within the dictionary which means 'B' is stored as a key and the value 1 is stored as a value within the dictionary 'dict' . So , the dictionary contains a pair of elements as {'B':1} .In the next step , 'o' is the letter for which the get() method searches in the dictionary .

 

This is not found within the 'dict' and therefore 1 is returned as result . Therefore ,

 

dict['o'] = 1

 

stores the new key and value pair that is 'o' and 1 into the dictionary object 'dict' and hence the dictionary contains the following data items :

{'B':1,'o':1}

In the next repetition of for loop , we get 'o' into the value of 'x' . And since , the value is already available in the dictionary 'dict' , the value that is returned is 1 by usage of the get() method for which the value 1 is added .

 

dict['o'] = 2

 

This means that the old value of 'o' is now updated to 2 in the dictionary and 'dict' contains the elements : { 'B':1,'o':2 } . In this manner , the 'dict' stores each letter as key and its number of occurrences as value .



Ref : Core Python Programming  by Dr.Nageswara Rao (Dreamtech Publications )