0% found this document useful (0 votes)
3 views25 pages

Module 3

Module 3 introduces dictionaries in Python, explaining their structure as collections of key-value pairs and how to create, access, modify, and delete items within them. It also covers dictionary operations, methods, and the concept of aliasing and copying. Additionally, the module discusses NumPy for mathematical operations on arrays, including features like slicing, masking, broadcasting, and data types.

Uploaded by

Manjula Jilla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

Module 3

Module 3 introduces dictionaries in Python, explaining their structure as collections of key-value pairs and how to create, access, modify, and delete items within them. It also covers dictionary operations, methods, and the concept of aliasing and copying. Additionally, the module discusses NumPy for mathematical operations on arrays, including features like slicing, masking, broadcasting, and data types.

Uploaded by

Manjula Jilla
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 3

Introductions to Dictionaries
● A collection of items where each item is represented by a key-value
pair
● Key and values are separated by :
● The elements are enclosed in { }
● d={key1:val1,key2:val2, key3:value3}
Example: d1={1:’A’, 2:’B’, 3:’C’}
● d2={‘name’:’ram’, ‘Rno’:72, ‘percentage’:72.5,’passed’:True}
How to create an empty dictionary
● Example:
d={ }
● Type(d): <class 'dict'>
Access the content of the dictionary
To access the elements of the dictionary, we should use a key, not
an index value.
Example:
d1={1:’A’, 2:’B’, 3:’C’}
d2={‘name’:’ram’,‘Rno’:72,‘percentage’:72.5,’passed’:True}
d1[1]=‘A’
d1[2]=‘B’

d2[‘Rno’]=72
d2[‘passed’]=True

1
DEPT. OF AIML,CBIT,KOLAR
Module 3

How to Add items to the dictionary


d1={1:’A’, 2:’B’, 3:’C’}
d1[4]=‘D’ #OUTPUT {1:’A’, 2:’B’, 3:’C’,4:’D’}
How to modify items of the dictionary
d1[1]=‘E’ # d1={1:’E’, 2:’B’ , 3:’C’}
How to delete items from the dictionary
del d1[1]
print[(d1)
Output: d1={ , 2:’B’, 3: ‘C’} # full dictionary delete del d1

Whether the dictionary is:


[Link] or ordered: The dictionary is an unordered collection
of items.
d1={1:’A’, 2:’B’, 3:’C’}
Print(d1) # any order you may get output
2. Mutable or immutable: Dictionary is mutable; we can add new
items in to the dictionary (keys->immutable, values-> mutable)
d1={1:’A’, 2:’B’, 3:’C’}
3. Unique or duplicate: keys are unique, values are either unique
or duplicates.
d1={1:’A’, 2:’B’, 3:’C’, 4:’A’}
Create a dictionary : start with the empty dictionary and add key:value
pairs. The empty dictionary is denoted {}:

2
DEPT. OF AIML,CBIT,KOLAR
Module 3

Another way to create a dictionary is to provide a list of key:value


pairs using the same syntax as the previous output

Hashing
● The order of the pairs may not be what was expected.
● Python uses complex algorithms, designed for very fast access, to
determine where the key:value pairs are stored in a dictionary.
● The reason is dictionaries are very fast, implemented using a
technique called hashing, which allows us to access a value very
quickly.
● By contrast, the list of tuples implementation is slow. If we wanted
to find a value associated with a key, we would have to iterate over
every tuple, checking the 0th element.

Dictionary operations
[Link]
● The del statement removes a key:value pair from a dictionary.
● Example: Dictionary contains the names of various fruits and the
number of each fruit in stock:

If someone buys all of the bananas, we can remove the entry from the
dictionary:

3
DEPT. OF AIML,CBIT,KOLAR
Module 3

If we then try to see how many bananas we have, we get an error

2. Updation
● Updating values in the dictionary
Example: Expecting more bananas soon, we might just change the
value associated with bananas:

A new shipment of bananas arriving could be handled like this:

3. Length
Returns the number of key:value pairs:

Dictionary Methods
● Dictionaries have a number of useful built-in methods
1. Keys
● In Python dictionaries, keys() is the method used to get all the
keys.
Example:

4
DEPT. OF AIML,CBIT,KOLAR
Module 3

Output:

OR

Example 2:

2. Values Method
The values() method in a Python dictionary returns all the values
stored in the dictionary.

Output:

3. items method

5
DEPT. OF AIML,CBIT,KOLAR
Module 3

The items() method returns key–value pairs from a dictionary as


tuples.

Output:

Example:2

Aliasing and copying


● Dictionaries, like lists, are mutable objects.
● Aliasing happens when two variables point to the same
dictionary in memory.

6
DEPT. OF AIML,CBIT,KOLAR
Module 3

● Any modification made through one variable automatically affects


the dictionary accessed through the other variable.
● Example 1:

● Eng :10 maths :20


Eng :23 maths :20
● Example 2:

● alias and opposites refer to the same object; copy refers to a fresh
copy of the same dictionary. If we modify alias, opposites is also
changed:


Numpy

● NumPy is a Python library that helps you do math with lists of


numbers quickly and easily.

● NumPy = a tool in Python used for fast calculations with


numbers, especially arrays (like lists)

Examples:

● It helps add, multiply, and do math on whole lists at once.

7
DEPT. OF AIML,CBIT,KOLAR
Module 3

● Used in data science and machine learning.


● Python list’s are not designed as mathematical objects. Rather, they
are purely a collection of items. In order to get a type of list which
behaves like a mathematical array or matrix, we use Numpy

● abbreviated numpy to np, this is conventional.


● [Link] takes a Python list as argument.
● The list [2, 3, 8] contains int’s, yet the result contains float’s. This
means numpy changed the data type automatically

Shape :

● The shape of an array means how many rows and columns


it has.
● If an array has 3 rows and 4 columns → shape = (3, 4)
● If it is just a list with 5 items → shape = (5,)

8
DEPT. OF AIML,CBIT,KOLAR
Module 3

Slicing
● select certain values from an array
● 1D arrays it works just like for normal python lists

NumPy Masking: Selecting elements of an array based on condition


Masking is one of the most powerful features of NumPy.
A mask is simply a boolean array (an array of True/False values) that you
use to select or modify certain elements of another array.
Step 1: Creating a Mask
import numpy as np
a = [Link]([230, 10, 284, 39, 76])
9
DEPT. OF AIML,CBIT,KOLAR
Module 3

print(a > 200)


a > 200 checks each element of a and returns True if it is greater than
200.
230 > 200 → True
10 > 200 → False
284 > 200 → True
39 > 200 → False
76 > 200 → False
OUTPUT: array([True, False, True, False, False])
This is called a boolean mask.

Step 2: Using the Mask to Modify Values

a[a > 200] = 0


“Wherever the condition a > 200 is True, set that element to 0.”
So:
230 → becomes 0
10 → stays same
284 → becomes 0
39 → stays same
76 → stays same
Result:
array([0, 10, 0, 39, 76])

10
DEPT. OF AIML,CBIT,KOLAR
Module 3

Step-by-step Explanation
1. Original array
a = [Link]([230, 10, 284, 39, 76]) # This is your list of numbers.
2. Cutoff value
cutoff = 200 #replace any number greater than 200 with 0.
3. Create an empty list
new_a = [] #This list will store the modified values.
4. Loop through each number
for x in a: #This goes through the array one element at a time.
5. Check each number
if x > cutoff:
new_a.append(0) #Replace it with 0
Otherwise
else:
new_a.append(x)
6. Convert back to NumPy array
a = [Link](new_a)
[0, 10, 0, 39, 76]

NumPy Broadcasting
● Broadcasting is a powerful feature in NumPy that allows you to
perform arithmetic operations on arrays of different shapes.
● Instead of requiring arrays to have the same size,

11
DEPT. OF AIML,CBIT,KOLAR
Module 3

● NumPy automatically expands (broadcasts) the smaller array so the


operation can be carried out.

Broadcasting works when the number of columns match or is 1, and the


number of rows match or is 1

The solution to multiplying c and b above is to specifically tell Numpy that


it must add that extra dimension as the second dimension of b. This is done
by using None to index that second dimension.

Step 1: Understand the shapes


c is a 2×3 array

12
DEPT. OF AIML,CBIT,KOLAR
Module 3

[[0, 1, 2],
[3, 4, 5]]
b is a 1D array with 2 elements:
[10, 100]
Step 2: b[:, None] adds a new axis
b[:, None] turns b into a column:
[[10],
[100]]
Now the shape becomes (2,1) instead of (2,)
Step 3: Broadcasting happens
c (2×3)*b[:,None] (2×1) # Broadcasting stretches (2,1) to (2,3):
[[10, 10, 10],
[100, 100, 100]]
Step 4: Element-wise multiplication
Multiply each row of c by the corresponding number in b:
Row 1: [0,1,2] * 10 → [0, 10, 20]
Row 2: [3,4,5] * 100 → [300, 400, 500]
Final output:
[[ 0, 10, 20],
[300, 400, 500]]

dtype in NumPy
dtype means data type.
It tells NumPy what type of value each element in an array
stores
for example:
● integers (int8, int16, int32, int64)
● unsigned integers (uint8, uint16)

13
DEPT. OF AIML,CBIT,KOLAR
Module 3

● floats (float16, float32, float64)


● booleans (bool)
NumPy arrays can store only one data type at a time.
So if you create an array, NumPy picks the smallest possible type that fits
your data.
uint8 (unsigned 8-bit integer)

● u = unsigned (cannot store negative numbers)


● int = integer
● 8 = uses 8 bits (1 byte)
● Range = 0 to 255

14
DEPT. OF AIML,CBIT,KOLAR
Module 3

So [Link]([10], dtype="uint8") means:


Store the value 10 as an unsigned integer that fits into 1 byte.

200 + 200 = 400


But 400 cannot fit inside a uint8 value because the maximum is 255.
So NumPy wraps around the value (this is called overflow).
How does it become 144?
To fit 400 into the 0–255 range:
400 - 256 = 144

Why 256?

Because:

● uint8 can hold exactly 256 values


(from 0 to 255)
So when you exceed 255, the value restarts at 0.
● Final Result

a + a = 144

uint16 means:

15
DEPT. OF AIML,CBIT,KOLAR
Module 3

● unsigned 16-bit integer can store values from 0 to 65,535

200 + 200 = 400

The result 400 is well within the allowed range of 0–65,535.

Therefore, NumPy stores the exact result:

400 #No wrap-around, no overflow.

Changing dtype
To change the dtype of an existing array, you can use the as type
method

a = [Link]([200], dtype='uint8')

uint8 means:

● unsigned 8-bit integer

● can store numbers from 0 to 255

Files

● Collection of data stored permanently on a storage device


● Data on non-volatile storage media is stored in named locations called
files.
● By reading and writing files, programs can save information between
program runs.

16
DEPT. OF AIML,CBIT,KOLAR
Module 3

Writing our first file

● Program that writes three lines of text into a file


● with is used to open a file and close it automatically.

Reading a file line-at-a-time

Read all the lines in the file, one at a time. This time, the mode argument is "r"
for reading

Output

Try to open a file that doesn’t exist, we get an error

Turning a file into a list of lines

● readlines()
● To turn a file into a list of lines in Python, use readlines() or list(f).

17
DEPT. OF AIML,CBIT,KOLAR
Module 3

● Fetch data from a disk file and turn it into a list of lines

Reading the whole file at once


● Read a whole file at once in Python using read()

18
DEPT. OF AIML,CBIT,KOLAR
Module 3

Binary files in Python


● Reading binary files means reading data that is stored in a binary format,
which is not human-readable.
● Unlike text files, which store data as readable characters, binary files store
data as raw bytes.
● Binary files store data as a sequence of bytes.
● Each byte can represent a wide range of values, from simple text characters
to more complex data structures like images, videos and executable
programs.

Different Modes for Binary Files in Python


When working with binary files in Python, there are specific modes we can use to
open them:

● 'rb': Read binary - Opens the file for reading in binary mode.

● 'wb': Write binary - Opens the file for writing in binary mode.

● 'ab': Append binary - Opens the file for appending in binary mode.

1. Open a binary file

Use 'rb' → read binary mode

f = open("[Link]", "rb")

2. Read full binary content

read() → reads the entire file as bytes

f = open('[Link]', 'rb')
data = [Link]()

19
DEPT. OF AIML,CBIT,KOLAR
Module 3

print(data)
[Link]()

✔ Output will be in bytes format → starts with b'...

3️. Read binary file line by line

readlines() → returns a list of binary lines

with open('[Link]', 'rb') as f:


lines = [Link]()
for line in lines:
print(line)

✔ Each line is also in bytes

4. Always close the file

If you use open(), then:

[Link]()

If you use with open(), Python closes it automatically.

Output

20
DEPT. OF AIML,CBIT,KOLAR
Module 3

Directories
● Directories are folders on your computer that hold files and other folders.
● A file system is how your computer organizes files and folders.
● Directories can also contain other directories
file = open("[Link]", "r")

● If the file is in another folder, you must give the path (the address of the
file).


21
DEPT. OF AIML,CBIT,KOLAR
Module 3

Output: ['karina \n', 'Rajan \n', 'Yogananda\n', 'Hemanth\n', 'vinth\n', 'vinay\n']

Fetching from web

Open a Website:

Output:

Fetching from the web


● This Python program downloads a webpage using [Link].
● It takes the URL [Link] and saves the webpage
content into a file named college_website.html.

22
DEPT. OF AIML,CBIT,KOLAR
Module 3

urlretrieve() is a function that downloads data from a given URL and saves it
directly into a file.

● destination_filename → the name of the file where the downloaded


content will be saved.
● After saving, it prints a message saying the file has been created.

Output

After downloading, if you open the .html file in Notepad, you will see the
HTML code/content of the webpage.

23
DEPT. OF AIML,CBIT,KOLAR
Module 3

Python program that downloads and displays a webpage using the requests
module.
Pip install requests in CD(change directory)

Opening the remote URL returns the response from the server. That response
contains several types of information, and the requests module allows us to
access them in various ways. On line 5, we get the downloaded document as a
single string. We could also read it line by line as follows:

24
DEPT. OF AIML,CBIT,KOLAR
Module 3

Output:

25
DEPT. OF AIML,CBIT,KOLAR

You might also like