PYTHON PROGRAMMING
Code: 1BPLCK105B/205B
Dr. SURESHA V
A Simplified Notes As per VTU Syllabus
2025 Scheme
MODULE 3
Dictionaries, NumPy, Files
Professor & Principal
Dept. of E&CE
K.V.G. College of Engineering, Sullia, D.K-574 327
Affiliated to Visvesvaraya Technological University
Belagavi - 590018
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
MODULE 3
Module 3: Dictionaries, Numpy, Files
Syllabus:
• Dictionaries: Dictionary operations, dictionary methods, aliasing and
copying.
• Numpy: About, Shape, Slicing, masking, Broadcasting, dtype.
• Files: About files, writing our first file, reading a file line-by-line, turning
a file into a list of lines, reading the whole file at once, working with
binary files, Directories, fetching something from the Web.
• Chapter: 5.4, 6.1-6.5, 7.1-7.8
• Text Book: Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris
Meyers- How to think like a computer scientist: learning with Python 3.
Green Tea Press, Wellesley, Massachusetts,2020
Chapter 5.4: Dictionaries
5.4.1 Introduction:
o Dictionaries are a built-in data type, used to store data values in key:
value pairs.
o Each key: value pair is called an element of the dictionary.
o Dictionaries are written with curly brackets and have keys and values.
o The key: value pairs of the dictionary are separated by commas. Each
pair contains a key and a value separated by a colon.
o Indexes for dictionaries are called keys.
o Dictionary items are ordered, changeable, and do not allow duplicates.
o The keys, which can be any immutable type, and the values are mutable.
o Dictionaries can use many different data types, not just integers.
o Examples:
fruits = {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
5.4.1 Dictionary operations
o Dictionaries have several useful built-in operations. Common operations
include
1. Creating a Dictionary
2. Accessing Dictionary items
3. Modifying Dictionary items
4. Deleting Dictionary items.
1. Creating a Dictionary:
In Python, dictionaries store data as key-value pairs. It is created
using curly braces ({}). Example capitals = {"Maharashtra":"Mumbai",
Telangana": "Hyderabad", "Karnataka":"Bengaluru"}.
2. Accessing Dictionary:
o Accessing Values by Key: The most direct ways to retrieve a value
associated with a specific key is using square brackets []. Example
>>> my_dict = {'fruit': 'apple', 'colour': 'blue', 'age': 25}
>>> print(my_dict['fruit']) # Output: apple
3. Modifying Dictionary items:
o In Python, dictionaries are mutable, and you can modify them by
changing existing values, adding new key-value pairs, or removing
items. We can change the value of a specific item by referring to its
key name. For example, change the "year" to 2018 in the following
dictionary.
>>> thisdict= {"brand": "Ford", "model": "Mustang", "year": 1964}
>>> thisdict["year"] = 2018
>>> thisdict= {"brand": "Ford", "model": "Mustang", "year": 2018}
o The update() method will update the dictionary with the items from
the given argument. For example, update the "year" of the car by
using the update() method:
>>> thisdict= {"brand": "Ford","model": "Mustang", "year": 1964}
>>> [Link]({"year": 2020})
>>> thisdict= {"brand": "Ford",model": "Mustang", "year": 2020}
o update the dictionary with the items. Example
>>> inventory = {"apples": 430, "bananas": 312, "oranges": 525,
"pears": 217}
>>> inventory["bananas"] = 50
>>> print(inventory) # Output
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 50}
>>> inventory["bananas"] += 200
>>> print(inventory)
{'pears': 0, 'apples': 430, 'oranges': 525, 'bananas': 250}
o The len() function also works on dictionaries; it returns the number of
key: value pairs. Example
>>> inventory = {"apples": 430, "bananas": 312, "oranges": 525,
"pears": 217}
>>> len(inventory)# Output 4
4. Deleting Dictionary items: We can delete items from a dictionary
using del dictionary[key] for a specific key. Example
>>> inventory = {"apples": 430, "bananas": 312, "oranges": 525,
"pears": 217}
>>> del inventory["bananas"]
>>> print(inventory) # Output
{'apples': 430, 'oranges': 525, 'pears': 217}
5.4.2 Dictionary methods: Dictionaries have several useful built-in
methods.
1. keys() method
2. values() method
3. items() method
o Accessing All Keys, Values, or Items: We can access all components of
a dictionary using methods.
o keys() method: It returns a view of all keys in the dictionary, which
are often used in loops. example
>>> my_dict = {'fruit': 'apple', 'colour': 'blue'}
>>> for key in my_dict.keys():
>>> print(key) # Output: fruit, color
o values() method: it returns a view of all values in the dictionary.
>>> my_dict = {'fruit': 'apple', 'color': 'blue'}
>>> for key in my_dict.values():
>>> print(key) # Output: apple, blue
o items() method: Returns a view of all key-value pairs as a list of
tuples. This is ideal for iterating through both keys and values
simultaneously.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
Example:
>>> my_dict = {'fruit': 'apple', 'color': 'blue'}
>>> for key, value in my_dict.items():
>>> print(f"The key is {key} and the value is {value}")
# Output:
# The key is fruit and the value is apple
# The key is color and the value is blue
o The in and not in operators in the dictionary: These operators
are used to test if a key is in the dictionary. Example
5.4.3 Aliasing and copying
▪ Aliasing
o Aliasing occurs when multiple variables refer to the same dictionary
object in memory.
o Since dictionaries are mutable, changes made through one variable will
be reflected in all other variables that point to that same object.
o This means that changes made to the object through one variable name
will be reflected in all other variables that reference the same
object. Example
>>> original_dict = {'a': 1, 'b': 2}
>>> alias_dict = original_dict # Aliasing occurs here
>>> alias_dict['b'] = 99 # Change made through the alias
>>> print(original_dict['b']) # Output: 99 - the original is affected
▪ copying
o In Python, the copy() method is a built-in dictionary method used to
create a shallow copy of a dictionary.
o A shallow copy creates a new dictionary object, so changes to the top-
level keys in the copy do not affect the original, and vice versa.
o If we want to modify a dictionary and keep a copy of the original, use the
copy method.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o Example:
>>> opposites = {"up": "down", "right": "wrong", "yes": "no"}
>>> alias = opposites
>>> copy = [Link]() # Shallow copy
o alias and opposites refer to the same object; copy refers to a fresh copy
of the same dictionary. If we modify the alias, opposites is also changed
>>> alias["right"] = "left"
>>> opposites["right"]
'left'
o If we modify a copy, opposites are unchanged.
>>> copy["right"] = "privilege"
>>> opposites["right"]
'left'
5.4.4 Counting letters
o There are various methods to count the frequency of characters in a
given string. One simple method to count the frequency of each
character is by using a dictionary.
o The idea is to traverse through each character in the string and keep a
count of how many times it appears. example
o We can count the letters in a Python string using a dictionary with a
simple for loop and the get() method. Example
Output:
o It might be more appealing to display the frequency table in alphabetical
order. We can do that with the items and sort methods.
>>> letter_items = list(letter_counts.items())
>>> letter_items.sort()
>>> print(letter_items)
[('M', 1), ('i', 4), ('p', 2), ('s', 4)]
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
• Difference Between Mutable and Immutable Data Type
• Compare List versus Dictionaries Data Types
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
Chapter 6 : NumPy
6.1 Introduction:
o NumPy stands for Numerical Python.
o NumPy is a Python library used for working with arrays.
o It provides support for large, multi-dimensional arrays and matrices,
along with a vast collection of high-level mathematical functions to
operate on these arrays efficiently.
o It is a fundamental library in Python for scientific computing.
▪ Why NumPy
o It provides a high-performance, multi-dimensional array object and a
comprehensive library of functions designed for numerical computing.
o It is significantly faster and more memory-efficient than standard Python
lists, making it the fundamental package for scientific computing.
o It offers a vast collection of high-level mathematical functions for tasks
such as:
- Linear algebra (e.g., matrix multiplication, inversion, eigenvalues).
- Statistical operations (e.g., mean, median, standard deviation).
- Fourier transforms and random number generation.
o Memory Efficiency: NumPy arrays use less memory than Python lists for
storing large, homogeneous numerical data, which is crucial when
working with large datasets.
o The standard Python data types are not very suited for mathematical
operations. Example:For example, suppose we have the list a = [2, 3, 8].
If we multiply this list by an integer, we get:
>>> a = [2, 3, 8]
>>> 2 * a
[2, 3, 8, 2, 3, 8]
o Suppose multiplying by a float is not even allowed:
>>> a = [2, 3, 8]
>>> 2 * a
>>> 2.1 * a
TypeError: can't multiply sequence by non-int of type 'float'
o This is because Python lists are not designed as mathematical objects.
Rather, they are purely a collection of items. In order to get a type of list
that behaves like a mathematical array or matrix, we use Numpy.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o NumPy aims to provide an array object that is up to 50x faster than
traditional Python lists because NumPy arrays are stored at one
continuous place in memory, unlike lists, so processes can access and
manipulate them very efficiently.
o Arrays are very frequently used in data science, where speed and
resources are very important.
▪ NumPy Getting Started:
o Once NumPy is installed, it can be used by adding the import keyword:
import numpy
>>> import numpy # Now NumPy is imported and ready to use.
o Example
>>>import numpy
>>>arr=[Link]([1, 2, 3, 4, 5])
>>>print(arr) # output [1 2 3 4 5]
o NumPy as np: NumPy is usually imported under the np alias. An alias
means an alternate name for referring to the same [Link] an alias
with the as keyword while importing:
>>> import numpy as np
o Now the NumPy package can be referred to as np instead of numpy.
>>>import numpy as np
>>>arr=[Link]([1, 2, 3, 4, 5])
>>>print(arr) # output [1 2 3 4 5]
o To get a type of list that behaves like a mathematical array or matrix, we
use [Link] 1
>>> import numpy as np
>>> a = [Link]([2, 3, 8])
>>> 2.1 * a
array([ 4.2, 6.3, 16.8])
o The list [2, 3, 8] in above example contains int’s, yet the result contains
floats. This means numpy changed the data type automatically for us.
o Example 2: multiply together arrays.
>>> import numpy as np
>>> a = [Link]([2, 3, 8])
>>> a * a
array([ 4, 9, 64])
>>> a**2
array([ 4, 9, 64])
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
6.2 Shape
o One of the most important properties an array is its shape.
o In NumPy, the shape of an array refers to the number of elements along
each dimension of the array. It is represented as a tuple, where each
integer in the tuple indicates the size of the corresponding dimension.
o Example:
o To get the shape of an array, we use shape:
o Example 1:
>>> import numpy as np
>>> a = [Link]([2, 3, 8])
>>> [Link] # output (3,)
o Example 2:
>>> b = [Link]([[2, 3, 8],[4, 5, 6],])
>>> [Link] # output (2, 3)
o Example 3:
import numpy as npy
# creating a 2-d array
arr1 = [Link]([[1, 3, 5, 7], [2, 4, 6, 8]])
# creating a 3-d array
arr2 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print([Link])
print([Link])
# Output:
(2,4)
(2, 2, 2)
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
6.3 Slicing
o NumPy array slicing is a powerful method for extracting specific
portions (subsets) of data from an array.
o The general syntax for slicing is arr[start:stop:step]
o This technique applies to arrays of any dimension.
o For 1D arrays, it works just like for normal Python lists. Example
>>> a = [Link]([2, 3, 8])
>>> a[2] # Output 8
>>> a[1:] # [Link]([3, 8])
o However, when dealing with higher-dimensional arrays, something else
happens:
>>> b = [Link]([[2, 3, 8],[4, 5, 6],])
>>> b[1] # Output array([4, 5, 6])
>>> b[1][2] # Output array 6
o By using b[1], returns the 1st row along the first dimension, which is
still an array. After that, we can select individual items from that. This
can be abbreviated to:
>>> b[1, 2] # Output 6
o But what if I wanted the 1st column instead of the first row? Then we
use: to select all items along the first dimension, and then a 1:
>>> b[:, 1] # array([3, 5])
6.4 Masking
o Masking in NumPy refers to the process of selectively working with
elements within an array based on a boolean condition.
o This is done using a Boolean mask (an array of True/False values)
o This technique is used to filter, select, or modify elements of an array
based on a Boolean condition.
o Suppose we have an array, and we want to throw away all values above
a certain cutoff. For example
>>> a = [Link]([230, 10, 284, 39, 76])
>>> cutoff = 200
>>> a > cutoff
[Link]([True, False, True, False, False])
o Example 2: Filtering Data: Extracting elements that meet a certain
condition.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
mask = arr > 25
filtered_arr = arr[mask] # Selects elements where mask is True
# Output: [30 40 50]
o Example 3: Modifying Elements: Changing values in an array based
on a condition.
import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
arr[arr > 30] = 100 # Replace values greater than 30 with 100
# Output: [ 10 20 30 100 100]
o Example 4: Multiple Conditions: Using bitwise logical operators (& for
AND, | for OR, ~ for NOT) to combine conditions.
arr = [Link]([10, 20, 30, 40, 50])
mask = (arr > 15) & (arr < 45)
filtered_arr = arr[mask]
# Output: [20 30 40]
6.5 Broadcasting
o NumPy broadcasting is a mechanism that allows arithmetic operations
on arrays of different shapes and sizes by automatically expanding the
smaller array to match the shape of the larger one
o It enables element-wise operations without requiring explicit reshaping
or repeating of data, leading to more concise and efficient code.
o Examples:
1. Broadcasting a Scalar: Adding a scalar to an array is the simplest
form of broadcasting. The scalar is conceptually stretched to match
the shape of the array.
import numpy as np
a = [Link]([1, 2, 3])
b = 2
# [Link] is (3,), b is a scalar
# NumPy conceptually treats 'b' as an array of shape (3,) with values
[2, 2, 2]
result = a + b # result is [3, 4, 5]
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o Example 2: Broadcasting takes place when you perform operations
between arrays of different shapes. For instance
o In the above example, the shapes of a and b don’t match. To proceed,
Numpy will stretch b into a second dimension, as if it were stacked three
times upon itself. The operation then takes place element-wise.
CHAPTER 7: FILES
7.1 About files:
o Variables in the programs store data while the program is running.
o But if we want our data to persist even after our program has finished,
we need to save it to a file.
o A file is a collection of data stored on a device like a hard drive, which
can contain anything from documents and images to videos and software
instructions.
o Python also supports file handling and allows users to handle files, i.e.
read and write files, along with many other file handling options.
o Data on non-volatile storage media is stored in named locations called
files.
o There are mainly TWO types of data files: Text Files and Binary Files
o TEXT FILE: Stores the data in the form of a string. A text file consists of
human-readable characters, which can be opened by any text editor.
[Link], .c, .cpp, .py
o BINARY FILE: Stores in the form of bytes. Binary files are made up of
non-human-readable characters and symbols, which require specific
programs to access their contents. Example .jpg, .gif or .png
▪ Advantages of files: Data is stored permanently, updating becomes
easy, Data can be shared among various programs, A Huge amount of
data can be stored.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
▪ File operations: In Python, a file operation takes place in the following
order
1. Open a file
2. Read or write operation
3. Close the file
7.2 Writing our first file
o In Python, files are written using the built-in open() function along with
specific file modes ('w' for write, 'a’ for append) and
the write() or writelines() methods.
o It is best practice to use the with statement to ensure the file is
automatically closed.
o Two modes for write operation:
1. Write mode ‘w’: replace the old data with new data
2. Append mode ‘a’: append the new data to old data
o Syntax:
f= open (‘filename’, ’w’)
[Link](‘Happy day!’)
[Link]()
o Example: Write mode
Program: Output:
o Another simple program that writes three lines of text into a file:
Program: Output:
o In this example, the variable myfile refers to the new handle object. On line 1, the
open function takes two arguments. The first is the name of the file, and the second
is the mode. Mode "w" means that we are opening the file for [Link] mode
"w", if there is no file named [Link] on the disk, it will be created.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o If there already is one, it will be replaced by the file we are writing. To put data in
the file we invoke the write method on the handle, shown in lines 2, 3 and 4 above.
7.3 Reading a file line-at-a-time
o The following methods are used for read operations.
1. read(): reading the content of the file.
2. read (integer): Read Only Parts of the File, can also specify how
many characters you want to return
3. readline(): Read one line of the file, calling 2 times to read two
lines.
4. readlines(): read all lines from the file.
1. read(): reading the content of the file. The steps involved in these
operations are
▪ Step 1: Open your document file. For example, [Link], which
contains the following data using
▪ Step 2: To open the above file, use the built-in open() function.
▪ Step3: The open() function returns a file object, which has
a read() method for reading the content of the file, example
>>> import os
>>>f= open("[Link]",’r’)
>>> print([Link]())
>>> [Link]()
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o If the same file is located in a different location, you will have to specify
the file path, like this:
>>> import os
>>>f= open("C:\\Users\\myfiles\[Link]",’r’)
>>> print([Link]())
>>> [Link]()
▪ readline(): Read one line of the file. Example uses the same [Link] file
>>> import os
>>>f= open("[Link]",’r’)
>>> print([Link]())
>>> [Link]()
# Output:It reads the first line of the document
▪ read(integer): Read Only Parts of the File, can also specify how many
characters you want to return. example
>>> import os
>>>f= open("[Link]",’r’)
>>> print([Link](24))
>>> [Link]()
# Output: It reads the first 24 characters from the document
7.4 Turning a file into a list of lines
o It is often useful to fetch data from a disk file and turn it into a list of lines.
o Suppose we have a file containing our friends and their email addresses, one per
line in the file. But we’d like the lines sorted into alphabetical order. A good plan is
to read everything into a list of lines, then sort the list, and then write the sorted list
back to another file: Example
o The readlines method in line 3 reads all the lines and returns a list of the strings.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
7.5 Reading the whole file at once
o Another way of working with text files is to read the complete contents of
the file into a string, and then to use our string-processing skills to work
with the contents. Consider the following phrase saved in a file,
[Link]
o Use the following code to read the entire file using the read function and convert it
into a list of words, and count the number of words in the documents.
o The output
7.6 An example
o Many useful line-processing programs will read a text file line-by-line and do some
minor processing as they write the lines to an output file.
o They might number the lines in the output file, or insert extra blank lines after every
60 lines to make it convenient for printing on sheets of paper, or extract some specific
columns only from each line in the source file, or only print lines that contain a
specific substring. We call this kind of program a filter. Here is a filter that copies one
file to another, omitting any lines that begin with #:
o On line 2, we open two files: the file to read, and the file to write. From line 3, we
read the input file line by line. We write the line in the output file only if the
condition on line 5 is true.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
7.7 Directories
o A Directory, sometimes known as a folder, is a unit of organisational
structure in a computer's file system for storing and locating files or
other folders
o They serve as a way to group and manage files hierarchically.
o Files on non-volatile storage media are organised by a set of rules known
as a file system.
o File systems are made up of files and directories, which are containers
for both files and other directories.
o When we create a new file by opening it and writing, the new file goes in
the current directory (wherever we were when we ran the program).
o If we want to open a file somewhere else, we have to specify the path to
the file, which is the name of the directory (or folder) where the file is
located:
o To access any file from the folders or directories, need the file path.
o A path is a string of characters used to uniquely identify a location in a
directory structure.
o A path refers to the specific location or route through which a file or
directory can be accessed within a file system. Example
o When working with files in directories, it is a good idea to let Python deal
with all the slashes and escaping them. The [Link] module does this for
different operating systems.
o On Windows, paths are written using backslashes (\) as the separator
between folder names.
o Example for path: C:\Users\asweigart\Documents\[Link]
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
o If we want to open a file somewhere else, we have to specify the path to
the file, which is the name of the directory (or folder) where the file is
located: Example
>>> wordsfile = open("C:\\usr\\share\\dict//[Link]", "r")
>>> wordlist = [Link]()
>>> print(wordlist[:6])
['\n', 'A\n', "A's\n", 'AOL\n', "AOL's\n", 'Aachen\n']
7.8 What about fetching something from the web?
o Web scraping is the automated process of using software to extract large
amounts of data from websites.
o Web scraping in Python involves programmatically extracting data from
websites using a combination of Python libraries.
o Python's built-in urllib library is a foundational tool for web scraping,
primarily used to fetch the raw HTML content of a webpage.
o Here is a simple example that copies the contents at some web URL to a
local file.
o The urlretrieve function— just one call— could be used to download any
kind of content from the Internet.
o We’ll need to get a few things right before this works:
• The resource we’re trying to fetch must exist! Check this using a
browser.
• We’ll need permission to write to the destination filename, and the file
will be created in the “current directory” - i.e. the same folder that the
Python program is saved in.
• If we are behind a proxy server that requires authentication, (as some
students are), this may require some more special handling to work
around our proxy. Use a local resource for the purpose of this
demonstration!
• We need to make sure that if we use any data from the web, that we
check if the contents are still as we expect them to be.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
• So before you use data from the internet, make your program check if
the data is what you want it to be, before executing any code or
showing it to any important users!
o Here is a slightly different example using the requests [Link]
module is not part of the standard library distributed with python, we
read it directly into a string, and we print that string. Example
Module 3: Question Bank
1. Define a dictionary in Python. How is it different from a list or tuple?*
2. Explain dictionary operations such as insertion, deletion, lookup, and update
with examples.*****
3. Write a Python program to count the frequency of each word in a given
string using a dictionary.*****
4. What are dictionary methods? Explain any five commonly used dictionary
methods with examples.*****
5. Explain aliasing in dictionaries with a suitable example. Why can aliasing
lead to unexpected results?*
6. Differentiate between shallow copy and deep copy of a dictionary. Illustrate
dictionary copying using the copy() method.*****
7. Write a program to merge two dictionaries into one. If keys are common,
add their values.
8. What is NumPy? List its advantages over Python lists.
9. Explain the concept of shape of a NumPy array. How can you change the
shape of an array?
10. Write a Python program to create a 2D NumPy array and display:***
• number of dimensions
• shape
• data type
11. Explain array slicing in NumPy. How is slicing different from slicing in
Python lists?
12. What is masking in NumPy? Demonstrate how boolean indexing works with
an example.
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19
Python Programming(1BPLCK105B) - Module 3: Dictionaries, Numpy, Files
13. Explain broadcasting in NumPy. State the rules that NumPy follows while
broadcasting arrays.
14. Write a program to demonstrate broadcasting by adding a 1D array to a
2D array.
15. What is dtype in NumPy? How can you change the data type of an existing
NumPy array?
16. What is a file in Python? Explain different file modes with examples.
17. Write a Python program to write data into a text file and then read it line-
byline.*****
18. Explain the difference between:***
• reading a file line-at-a-time
• reading the whole file at once
• Provide code snippets for both.
19. What are binary files? How are they different from text files? Write a short
program to read a binary file.
20. Explain how Python works with directories. Write a program to:***
• list all files in a directory
• fetch data from a webpage and store it in a file
Acknowledgement:
My sincere thanks to the author Peter Wentworth, Jeffrey Elkner, Allen B.
Downey and Chris Meyers- , because the above contents are prepared from
there textbook “How to think like a computer scientist: learning with
python 3”. Green Tea Press, Wellesley, Massachusetts,2020
Prepared by:
Dr. Suresha V
Professor & Principal
Dept. of Electronics and Communication Engineering.
Reach me at: [Link]@[Link]
WhatsApp: +91 8310992434
Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20