0% found this document useful (0 votes)
7 views12 pages

Python Dictionary and File Handling Guide

Uploaded by

gu.chettiar04
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)
7 views12 pages

Python Dictionary and File Handling Guide

Uploaded by

gu.chettiar04
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

1. What is a dictionary in Python, and how does it differ from a list?


2. Write a Python program to create a dictionary that stores the names of three students as
keys and their marks as values. Print the marks of one student using their name.
3. Explain the purpose of the prettyprint (pprint) module in Python with an example.
4. A library wants to manage its collection by storing books' details. Each book has a title,
author, and year of publication. Design a dictionary to represent this data and
demonstrate how to print all book details neatly.
5. Create a program that stores people's names along with their age in a dictionary. Display
the age for a specific person if their name exists in the dictionary. If the name is not
present, add the person and their age to the dictionary.
6. Describe python methods used on dictionaries data.
7. Describe python methods used on string data.
8. In an online store, each product has a unique identifier like "A10HOME200", where:
● A10 represents the product series.
● HOME signifies the category (Home Appliances).
● 200 is the product ID.
Write a program to:
1. Print each character of the product code on a new line.
2. Extract and display the series, category, and product ID separately.

8. Write a program to store data about your friends’ birthdays note if name present in
dictionary print the name other wise if name is not present in the dictionary the update in the
dictionaries.

9. Write a program that counts the number of occurrences of each letter in a string. Using
setdefault() function.

10. Implement a program to show Tic tac toe game.


Module-4

1. Develop a Python program to read all the words from a text file, sort them alphabetically,
and write the sorted words (one per line) into a new text file. [Hint: Use string methods
split(), lower(), and list methods sort() and extend()].
2. Illustrate with an example program how the shelve module stores variables persistently.
3. Write a Python program using the shelve module to store a dictionary of student data
persistently. The dictionary should contain student names as keys and their scores as
values. Demonstrate how to retrieve and display this data in a subsequent program
execution.
4. A company maintains its monthly sales data in an Excel file named
monthly_sales.xlsx. Write a program using the openpyxl module to read the file
and calculate the total sales from the Sales column. Display the total sales value as
output.
5. An organization tracks sales of various products in an Excel file named
product_sales.xlsx. Develop a Python program to identify the product with the
highest sales by reading the data from the file using the openpyxl module.
6. A company wants to identify all transactions where the sales amount exceeds 20,000.
The data is stored in an Excel file named [Link]. Write a program using
the openpyxl module to filter and display these high-value transactions.
7. An Excel file named regional_sales.xlsx contains sales data categorized by
regions. Develop a program using the openpyxl module to calculate and display the
total sales for each region.
8. A company stores sales data in an Excel file. Develop a program how you would read
and process the data to calculate total sales using the openpyxl module
9. A company maintains product sales data in an Excel file named sales_data.xlsx.
Write a program using the openpyxlmodule to create a bar chart representing total
sales for each product category and save the updated workbook as
sales_chart.xlsx.
10. You are working with a CSV file containing customer feedback data. The file uses a pipe
(|) as the delimiter instead of a comma, and each row ends with a semicolon (;) instead
of the usual newline character. Your task is to illustrate how to read this file and convert
it into a standard CSV format using Delimiter and Line terminator keyword.
11. You are working with a CSV file containing data from weather sensors. The file uses a
tab (\t) as the delimiter and a colon (:) as the line terminator. Write a program to read
this file, process the data, and convert it into a standard CSV format with commas as
delimiters and newlines as line terminators.
12. A company provides employee information in a CSV file where fields are separated by
semicolons (;), and rows are separated by a tilde (~). Develop a Python program to
read this file and convert it into a standard CSV format using commas as delimiters and
newlines as line terminators.
13. You are working with financial records stored in a CSV file. The data uses a hash (#) as
the field delimiter and a pipe (|) as the row terminator. Write a Python program to read
the data and reformat it into a standard CSV file with commas and newlines.
14. An inventory management system generates CSV files where the fields are separated
by asterisks (*), and each row ends with a dollar sign ($). Your task is to write a Python
program to read and reformat this file into a standard CSV format.
15. A log file stores events in a CSV-like format where fields are separated by colons (:),
and rows are separated by double newline characters (\n\n). Write a Python program
to parse this file and convert it into a standard CSV format using commas as delimiters
and single newlines as row terminators.
16. You are working as a data analyst for a company that processes large datasets received
from various vendors. These datasets are in CSV format, and each file contains a
header row that describes the columns. However, the company’s proprietary data
processing software cannot handle files with headers, Develop a python program to
remove the header in all the files for the further process in a company.
17. You are working with datasets provided by multiple vendors. These CSV files include a
metadata section at the top, consisting of 5 descriptive rows before the actual data
starts. Your company’s analysis tools require only the data rows. Write a Python
program to remove the first 5 rows from each file in a directory and save the cleaned
files for further processing.
18. As part of a data integration project, you receive CSV files where the first row contains
column headers and the last row contains summary statistics. Your company’s software
requires files with only the raw data rows. Develop a Python program to remove the first
(header) and last (summary) rows from these files and save the cleaned versions.
19. Develop a program [Link] that takes a number N from the command line
and generates an N×N division table (where each cell contains the result of dividing row
number by column number) in an Excel spreadsheet.
20. Write a program [Link] that takes a number N from the command line and
creates an N×N power table in an Excel spreadsheet, where each cell contains the result
of raising the row number to the power of the column number.
21. Develop a program [Link] that takes a number N from the command line
and creates an N×N multiplication table in an Excel spreadsheet

1. def sort_words_in_file(input_filename, output_filename):


try:
# Open and read the input file
with open(input_filename, 'r') as file:
content = [Link]()
# Split the content into words, convert to lowercase and sort
words = [Link]()
words = [[Link]() for word in words] # Convert all words to lowercase
[Link]() # Sort words alphabetically

# Write the sorted words into the output file


with open(output_filename, 'w') as output_file:
for word in words:
output_file.write(word + '\n') # Write each word on a new line

print(f"Sorted words have been written to {output_filename}")

except Exception as e:
print(f"An error occurred: {e}")

# Example usage
input_filename = 'input_text.txt' # Input file containing text
output_filename = 'sorted_words.txt' # Output file to write sorted words

# Sort words in the input file and write them to the output file
sort_words_in_file(input_filename, output_filename)

Module- 5
1. Write a function to print time in HH:MM:SS format and another function to add two time
objects
2. Write a function to print time in HH:MM:SS format and another function to add time
object with seconds=7000.
3. Implement a Circle class with attributes radius and diameter and another
attribute point on the circumference, which is an instance of the Point class.
The Point class should have x and y coordinates. Write methods to:
● Calculate the circle’'s area.
● Display the circle’'s radius and diameter.
4. Difference between class attributes and instance attributes.
5. How do you pass objects as argument to a function and a return value.
6. Explain different types of object copy methods
7. Write a program to create a class Point with empty implementation and create 2 objects
with instance attributes
class Point:

def __init__(self, x, y):

self.x = x

self.y = y

class Circle:

def __init__(self, radius, diameter, point_on_circumference, center_point):

[Link] = radius

[Link] = 2 * radius

self.point_on_circumference = self.calculate_circumference_point(center_point)
def calculate_circumference_point(self, center):

# Assuming we want the point on the circumference directly to the right of the center

return Point(center.x + [Link], center.y)

# Add other methods like calculating area, perimeter etc. as needed

import math

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

def __str__(self):

return f"Point({self.x}, {self.y})"

class Circle:

def __init__(self, radius, point_on_circumference):

[Link] = radius

[Link] = 2 * radius

self.point_on_circumference = point_on_circumference

def area(self):

# Area of a circle = π * radius^2


return [Link] * ([Link] ** 2)

def display(self):

# Display the radius and diameter

print(f"Radius: {[Link]}")

print(f"Diameter: {[Link]}")

print(f"Point on circumference: {self.point_on_circumference}")

# Example usage

point = Point(3, 4) # Point on the circumference

circle = Circle(5, point)

# Display the circle's details

[Link]()

# Calculate and display the area of the circle

print(f"Area of the circle: {[Link]()}")


Deep copy in Python

 A deep copy creates a new compound object before inserting copies of the items found
in the original into it in a recursive manner.

 It will first construct a new collection object and then recursively populate it with copies of
the child objects found in the original. It means that any changes made to a copy of the
object do not reflect in the original object.
import copy

a = [[1, 2, 3], [4, 5, 6]]

# Creating a deep copy of the nested list 'a'

b = [Link](a)

# Modifying an element in the deep-copied list

b[0][0] = 99

print(b)

Output

[[99, 2, 3], [4, 5, 6]]

Explanation:

 [Link]() method creates a completely independent copy of the original object,


including all nested elements. Changes made to deep_copied do not affect the original
list a.

 nested elements of the original list a are recursively duplicated to ensure that even
deeply nested objects are entirely independent in the copied list.
Shallow copy in Python

 A shallow copy creates a new object but retains references to the objects contained
within the original. It only copies the top-level structure without duplicating nested
elements.

 Changes made to a copy of an object do reflect in the original object. In python, this is
implemented using the “[Link]()” function.

import copy

a = [[1, 2, 3], [4, 5, 6]]

# Creating a shallow copy of the nested list 'original'

b = [Link](a)

# Modifying an element in the shallow-copied list

b[0][0] = 99
# Printing the original and shallow-copied lists

print(b)

Output

[[99, 2, 3], [4, 5, 6]]

Explanation:

 A shallow copy only copies the outer structure, retaining references to the nested
objects. In this case, the inner lists are shared between original and shallow_copied.

 As a result, changes to the nested elements in shallow_copied (e.g., modifying


shallow_copied[0][0]) are also reflected in original.
class Point:
pass # Empty implementation

# Creating two objects of the Point class


point1 = Point()
point2 = Point()

# Assigning instance attributes to both objects


point1.x = 3
point1.y = 4

point2.x = 5
point2.y = 6

# Displaying the attributes of both points


print(f"Point 1: x = {point1.x}, y = {point1.y}")
print(f"Point 2: x = {point2.x}, y = {point2.y}")

output
Point 1: x = 3, y = 4 Point 2: x = 5, y = 6

You might also like