Python Programming Unit - III, IV, V
Python Programming Unit - III, IV, V
Dr. D.Kavitha
Creating Dictionary
A dictionary is a collection of an unordered set of key:value pairs.
Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs
separated by commas.
There is a colon (:) separating each of these key and value pairs.
left of the colon -- keys
right of the colon -- values.
dictionaries are indexed by keys.
Here a key along with its associated value is called a key:value pair.
Dictionary keys are case sensitive. the keys are unique within a dictionary.
Dictionary keys are immutable type and can be either a string or a number. Duplicate keys are
not allowed in the dictionary
Creating Dictionary
dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3, ………,key_n:value_n}
empty dictionary -- dictionary_name = { }
pizza = {"pepperoni":3, "calzone":5, "margherita":4}
mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
The dict() Function: dict([**kwarg]) kwarg = value
numbers = dict(one=1, two=2, three=3)
Print(numbers)
{'one': 1, 'two': 2, 'three': 3}
The syntax for dict() function when iterables used is,
dict(iterable[, **kwarg])
1. >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
Accessing and Modifying key:value Pairs in Dictionaries
The syntax for accessing the value for a key in the dictionary is, dictionary_name[key]
The syntax for modifying the value of an existing key or for adding a new key:value pair to a
dictionary is, dictionary_name[key] = value
the ordering of key:value pairs does not matter in dictionaries.
Slicing is not allowed since they are not ordered like lists.
Dictionaries remember the order in which the key:value pairs were inserted.
check for the presence of a key in the dictionary using in and not in membership
operators. It returns either a Boolean True or False value. For example,
1. >>> clothes = {"rainy":"raincoats", "summer":"tees", "winter":"sweaters"}
2. >>> "spring" in clothes
False
3. >>> "spring" not in clothes
True
Populating Dictionaries with key:value Pairs
1. start with an empty dictionary { }, then use the update() method to assign a value to the
key using assignment operator.
1. >>> countries = {}
2. >>> countries.update({"Asia":"India"})
3. >>> countries.update({"Europe":"Germany"})
5. >>> countries
{'Asia': 'India', 'Europe': 'Germany'}
6.>>>countries[„Africa‟] = “Zimbambwe”
If the key does not exist, then the key:value pairs will be created automatically and added to
the dictionary
Removing an item from Dictionary
To delete the key:value pair, use the del statement followed by the name of the dictionary along with
the key you want to delete.
del dict_name[key]
1. >>> animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
2. >>> del animals["c"]
3. >>> animals {'r': 'raccoon', 'm': 'moose'}
Pop -- Removes the removes the key from the dictionary and returns its value.
Animal = animals.pop(„m‟)
popitem() -- removes and returns an arbitrary (key, value) tuple pair from the dictionary
Popped = animals.popitem()
clear() -- to remove all items from a dictionary at once.
Animals.clear()
Traversing of Dictionary/Accessing an item
A for loop can be used to iterate over keys or values or key:value pairs in
dictionaries.
If you iterate over a dictionary using a for loop, then, by default, you will
iterate over the keys.
If you want to iterate over the values, use values() method and for iterating
over the key:value pairs, specify the dictionary‟s items() method explicitly.
The dict_keys, dict_values, and dict_items data types returned by dictionary
methods can be used in for loops to iterate over the keys or values or key:value
pairs.
Traversing of Dictionary
1. currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen", "Germany": "Euro"}
2. def main():
3. print("List of Countries")
4. for key in currency.keys():
5. print(key)
6. print("List of Currencies in different Countries")
7. for value in currency.values():
8. print(value)
9. for key, value in currency.items():
10. print(f"'{key}' has a currency of type '{value}'")
11. if __name__ == "__main__":
12. main()
Built-In Functions Used on Dictionaries
3. >>> american_flowers.add("orchids")
9. >>> american_flowers.symmetric_difference(european_flowers)
• Built-in functions include len(), which returns the length of the list; max(), which returns the
maximum element in the list; min(), which returns the minimum element in the list and sum(),
which returns the sum of all the elements in the list.
• An individual elements in the list can be accessed using the index operator [].
• Lists are mutable sequences which can be used to add, delete, sort and even reverse list
elements.
• The built-in function dict() returns a new dictionary initialized from an optional keyword
argument and a possibly empty set of keyword arguments.
• The for loop is used to traverse all the keys in the dictionary.
• The del dictionaryName[key] statement is used to delete an item for the given key.
• Dictionary methods like keys(), values(), and items() are used to retrieve the values.
• Methods like pop() and update() are used to manipulate the dictionary key:value pairs.
Sets and Tuples
• Tuple is an immutable data structure comprising of items that are ordered and heterogeneous.
• The set stores a collection of unique values and are not placed in any particular order.
• Add an item to the set using add() method and remove an item from the set using the remove() method.
• The issubset() or issuperset() method is used to test whether a set is a superset or a subset of another
set.
• Sets also provide functions such as union(), intersection(), difference(), and symmetric_difference().
PYTHON PROGRAMMING
UNIT III - LISTS
Dr. D.Kavitha
LISTS
List is a container that holds a number of items.
Each element or value that is inside a list is called an item. All the items in a
list are assigned to a single variable.
Lists can be simple or nested lists with varying types of values.
Lists are constructed using square brackets [ ] wherein you can include a list of
items separated by commas.
empty list - list_name = [ ] - item[]
Lists - store = ["metro", "tesco", "walmart", "kmart", "carrefour"]
list1 = [4, 4, 6, 7, 2, 9, 10, 15]
list2 = ['dog', 87.23,‟apple‟, 65, [9, 1, 8, 1]]
LISTS
Lists are:
Ordered - They maintain the order of elements.
Mutable - Items can be changed after creation.
Allow duplicates - They can contain duplicate values.
Basic List Operations
+ sign – lists concatenation
* sign - create a repeated sequence of list items
1. >>> list_1 = [1, 3, 5, 7]
2. >>> list_2 = [2, 4, 6, 8]
3. >>> list_1 + list_2
[1, 3, 5, 7, 2, 4, 6, 8]
4. >>> list_1 * 3
[1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
5. >>> list_1 == list_2
False
6. >>> 5 in list_1
True
The list() Function
The built-in list() function is used to create a list. The syntax for list()
function is, list([sequence])
where the sequence can be a string, tuple or list itself. If the optional
sequence is not specified then an empty list is created.
For example,
1. >>> quote = "How you doing?"
2. >>> string_to_list = list(quote)
3. >>> string_to_list
['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
Indexing and Slicing in Lists
The syntax for accessing an item in a list is, list_name[index]
>>> superstore[3]
'kmart„
>>> superstore[-3]
'walmart'
Modifying Items in Lists
Lists can be modified.
>>> fauna = ["pronghorn", "alligator", "bison"]
>>> fauna[0] = "groundhog“ >>> fauna[-1] = "beaver"
1. >>> zoo = ["Lion", "Tiger", "Zebra"]
2. >>> forest = zoo
Slicing of lists : list_name[start:stop:[step]]
fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
fruits[1:3]
['pineapple', 'blueberries']
>>> fruits[1:4:2]
['pineapple', 'mango']
fruits[::-1]
['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
Adding Items to a List
1. use the append() method to add an element to the end of a Python list.
fruits = ['apple', 'banana', 'orange']
fruits.append('cherry')
print('Updated List:', fruits) -- ['apple', 'banana', 'orange', 'cherry']
2. insert() method adds an element at the specified index.
fruits.insert(2, 'cherry')
print("Updated List:", fruits) -- ['apple', 'banana', 'cherry', 'orange']
3. use the extend() method to add elements to a list from other list.
numbers = [1, 3, 5]
even_numbers = [2, 4, 6]
numbers.extend(even_numbers)
print('Updated Numbers:', numbers) -- [1, 3, 5, 2, 4, 6]
Built-In Functions Used on Lists
1. >>> dir(list)
change the items of a list by assigning new values using the = operator
colors[2] = 'Blue
remove an item from a list using the remove() method.
numbers = [2,4,7,9] numbers.remove(4) [2, 7, 9]
del statement removes one or more items from a list.
del numbers[1] del numbers[:] del numbers del numbers[1:3]
Pop statement Returns and removes item present at the given index –
rightmost item.
Element = numbers.pop(1) numbers.pop()
Traversing Through a List
Along with list comprehensions, we also use lambda functions to work with lists.
While list comprehension is commonly used for filtering a list based on some conditions, lambda
functions are commonly used with functions like map() and filter().
They are used for complex operations or when an anonymous function is required.
square_numbers = [num ** 2 for num in numbers]
square_numbers = list(map(lambda num : num**2 , numbers))
Program 6.1: Program to Dynamically Build User Input as a List
list_1 = list(“Enter list items”)
print(f"List items are {list_1}")
list_items = input("Enter list items separated by a space ").split()
print(f"List items are {list_items}")
items_of_list = []
total_items = int(input("Enter the number of items "))
for i in range(total_items):
item = input("Enter list item: ")
items_of_list.append(item)
print(f"List items are {items_of_list}")
Program 6.2: Program to Illustrate Traversing of Lists Using the for loop
fast_food = ["waffles", "sandwich", "burger", "fries"]
for each_food_item in fast_food:
print(f"I like to eat {each_food_item}")
for each_food_item in ["waffles", "sandwich", "burger", "fries"]:
print(f"I like to eat {each_food_item}")
Program 6.4: Write Python Program to Sort Numbers in a List in Ascending Order
Using Bubble Sort by Passing the List as an Argument to the Function Call
def bubble_sort(list_items):
for i in range(len(list_items)):
for j in range(len(list_items)-i-1):
if list_items[j] > list_items[j+1]:
temp = list_items[j]
list_items[j] = list_items[j+1]
list_items[j+1] = temp
print(f"The sorted list using Bubble Sort is {list_items}")
def main():
items_to_sort = [5, 4, 3, 2, 1]
bubble_sort(items_to_sort)
if __name__ == "__main__":
main()
Nested Lists
A list inside another list is called a nested list.
1. >>> asia = [["India", "Japan", "Korea"],
["Srilanka", "Myanmar", "Thailand"],
["Cambodia", "Vietnam", "Israel"]]
2. >>> asia[0]
['India', 'Japan', 'Korea']
3. >>> asia[0][1]
'Japan'
4. >>> asia[1][2] = "Philippines"
The del Statement
You can remove an item from a list based on its index rather than its value. The difference
between del statement and pop() function is that the del statement does not return any
value
while the pop() function returns a value. The del statement can also be used to remove
slices from a list or clear the entire list.
1. >>> a = [5, -8, 99.99, 432, 108, 213]
2. >>> del a[0]
3. >>> a
[-8, 99.99, 432, 108, 213]
4. >>> del a[2:4]
5. >>> a
[-8, 99.99, 213]
6. >>> del a[:]
PYTHON PROGRAMMING
UNIT IV - FILES
Dr. D.Kavitha
Files
Two types of files – Text files and Binary files.
In text file, an End-of-Line (EOL) character is placed at the end of each line.
An End-of-File (EOF) marker is placed after the final character, which signals the
end of the file.
Files
File Path
file path -- which is basically a route so that the user or the program knows where the file is located.
Fully Qualified Path and Relative Path
Creating and Reading Text Data
open() – open a file.
file_handler = open(filename, mode) f1 = open(“example.txt",”x")
close() –
file_handler.close() f1.close()
Use of with Statements to Open and Close Files
with open (file, mode) as file_handler: with open(“a.txt”,w+) as f1, open(“b.txt”,w+) as f2:
Statement_1 .
Statement_2 .
with open(“example.txt",”x") as f1:
for line in f1:
print(line)
f1.close()
Mode Description
File Object Attributes
When the Python open() function is called, it returns a file object called a file handler(f1). Using this
file handler, you can retrieve information about various file attributes. For example,
1. >>> f1 = open("computer.txt", "w")
2. >>> print(f"File Name is {f1.name}") File Name is computer.txt
3. >>> print(f"File State is {f1.closed}") File State is False
4. >>> print(f"File Opening Mode is {f1.mode}") File Opening Mode is w
Attribute Description
f1.closed It returns a Boolean True if the file is closed or False otherwise.
f1.mode It returns the access mode with which the file was opened.
f1.name It returns the name of the file.
File Methods to Read and Write Data
When you use the open() function a file object is created. Here is the list of methods that can be
called on this object
If you have an object x and a file object f, which has been opened for writing, the simplest way to
pickle the object is, pickle.dump(x, f)
The dump() method writes a pickled representation of object x to the open file object f.
If f is a file object, which has been opened for reading, then the simplest way to unpickle the object
is, x = pickle.load(f)
The load() method reads a pickled object representation from the open file object f and return the
reconstituted object hierarchy specified therein.
Pickling is the standard way to make Python objects that can be stored and reused by other programs
or by a future invocation of the same program;
Reading and Writing CSV Files
CSV (Comma Separated Values) format is the most common import and export format for
spreadsheets and databases. Since a comma is used to separate the values, this file format is
aptly named Comma Separated Values
Reading and Writing CSV Files
CSV files have .csv extensions
To read from a CSV file use csv.reader() method. The syntax is,
csv.reader(csvfile)
To write to a CSV file, use the csv.writer() method. The syntax is,
csv.writer(csvfile)
1. import csv
2. def main():
3. with open('biostats.csv', newline='') as csvfile:
4. csv_reader = csv.reader(csvfile)
5. print("Print each row in CSV file")
6. for each_row in csv_reader:
7. print(",".join(each_row))
8. if __name__ == "__main__":
9. main()
Python os and os.path Modules
Python os module provides a portable way of using operating system dependent functionality.
For accessing the filesystems, use the os module.
To manipulate paths, use the os.path module.
Summary
Python supports two basic file types, namely text files and binary files.
• File objects can be used to read/write data to/from files. You can open a file with mode 'r' for
reading, 'w' for writing, and 'a' for appending.
• The read(), readline(), and readlines() methods are used to read data from a file.
• The write() and writes() methods are used to write data to a file.
• The file object should be closed after the file is processed to ensure that the content
is saved properly.
• The dictionary data can be read and written to a CSV file using DictReader() and DictWriter()
classes.
• The os Module methods are used to perform some important processing on files.
Object-Oriented Programming
class abcd:
def __init__(self,a):
self.a = a
print(f"Sample class method. Value is {self.a}")
obj = abcd(10)
The Constructor Method
The __init__() method defines and initializes the instance variables. It is invoked as soon as an object of a
class is instantiated.
The number of arguments during the instantiation of the class object should be equivalent to the number of
parameters in __init__() method (excluding the self parameter).
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to
do when the object is being created
Class instantiation uses function notation, wherein the class name is followed by parentheses ()
The self parameter is a reference to the current instance of the class, and is used to access variables that
belong to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of
any function in the class.
The remaining parameter variables must be supplied as arguments in the calling method
Classes with Multiple Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Inheritance
A class that is used as the basis for inheritance is called a superclass or base class or parent
class
A class that inherits from a base class is called a subclass or derived class or child class .
A derived class inherits variables and methods from its base class while adding additional
variables and methods of its own.
class DerivedClassName(BaseClassName):
<statement-1>
...
<statement-N>
Inheritance
Polymorphism
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
NumPy with Python
NumPy is the fundamental package for scientific computing with Python. It stands for
“Numerical Python.” It supports:
• N-dimensional array object
• Broadcasting functions
• Tools for integrating C/C++ and Fortran code
• Useful linear algebra, Fourier transform, and random number capabilities.
NumPy‟s main object is the homogeneous multidimensional array
NumPy‟s array class is called ndarray or array.
the individual data items are called elements
Arrays can be made up of any number of dimensions called as axes.
Length(dimension) – the total number of elements in that direction.
The size (array) -- total number of elements contained in an array in all the dimension.
The size of NumPy arrays are fixed;
All the rows are indicated by Axis-0 and all the columns are indicated by Axis-1.
the indexes range from 0 to length – 1.
Array indexes are 0-based. That is, if the length of a dimension is n, the index values
range from 0 to n – 1.
NumPy Arrays Creation Using array() Function
import numpy as np
n_array = np.array([1,2,3,4])
type(n_array) -- array([1, 2, 3, 4])
n_array.dtype -- dtype('int32')
array_list = np.array([[1,2,3], [4,5,6]]) -- array([[1, 2, 3], [4, 5, 6]])
array_tuple = np.array(((1,2,3), (4,5,6))) -- array([[1, 2, 3], [4, 5, 6]])
array_dtype = np.array([1,2,3,4], dtype = np.float64) -- array([1., 2., 3., 4.])
Array Attributes
Arrays creation with Initial values
Indexing, Slicing
Indexing, Slicing
Basic Arithmetic Operations