Lab: Working with collection types
The objective of this lab is to explore the critical functionality of lists, tuples, dictionaries,
and sets in Python. Participants will learn how to perform common operations such as
creation, accessing elements, adding and removing elements, iteration, and manipulation
using these data structures. Additionally, case studies will be provided to demonstrate
practical scenarios where each data structure can be used effectively. By the end of this lab,
learners should be able to:
Understand the properties and use cases of lists, tuples, dictionaries, and sets.
Perform essential operations on these data structures, including creation, accessing
elements, adding and removing elements, iteration, and manipulation.
Apply these data structures to solve real-world problems through case studies.
Overview:
# Data Structures Lab
# Introduction to Data Structures
"""
Lists:
- Ordered collection of items.
- Mutable (can be modified after creation).
- Use when you need a collection of items that can be changed.
Tuples:
- Similar to lists but immutable (cannot be changed after creation).
- Use when you have a collection of items that should not change.
Dictionaries:
- Collection of key-value pairs.
- Mutable and unordered.
- Use when you need to map keys to values.
Sets:
- Unordered collection of unique elements.
- Mutable (can be changed after creation).
- Use when you need to store unique elements and perform set operations.
"""
Step:1 Working with List
Open Visual Studio Code and create a new Python file named data_structures_lab.py type
below code to Create a list using different methods such as list literals and the list()
constructor., Access Elements, Add and Remove Elements, Iterate and Manipulate list
# Lists
# Creation
# Using list literals
my_list = [1, 2, 3, 4, 5]
# Using the list() constructor
another_list = list(range(1, 6))
print("Created list:", my_list)
print("Another list:", another_list)
# Accessing Elements
# By index
print("First element:", my_list[0])
print("Last element:", my_list[-1])
# Slicing
print("Sliced elements:", my_list[1:4])
# Adding and Removing Elements
# Adding elements
my_list.append(6)
print("After append:", my_list)
my_list.insert(2, 10)
print("After insert:", my_list)
# Removing elements
my_list.remove(3)
print("After remove:", my_list)
popped_element = my_list.pop()
print("Popped element:", popped_element)
print("After pop:", my_list)
# Iteration
# Using for loop
print("Iterating using for loop:")
for item in my_list:
print(item)
# Using list comprehension
print("Iterating using list comprehension:")
squared_list = [x ** 2 for x in my_list]
print(squared_list)
# Manipulation
# Sorting
my_list.sort()
print("Sorted list:", my_list)
# Reversing
my_list.reverse()
print("Reversed list:", my_list)
Step:2 Working with Tuple
Open visual studio code and create a new file with .py extension, Create a
tuple using different methods such as tuple literals and the tuple()
constructor, Demonstrate accessing elements by index, Iterate through
the tuple using a for loop.
# Tuples
# Creation
# Using tuple literals
my_tuple = (1, 2, 3, 4, 5)
# Using the tuple() constructor
another_tuple = tuple(range(1, 6))
print("Created tuple:", my_tuple)
print("Another tuple:", another_tuple)
# Accessing Elements
# By index
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
# Iteration
# Using for loop
print("Iterating using for loop:")
for item in my_tuple:
print(item)
Step:3 Working with Set
Create a set using different methods such as set literals and the set() constructor.
Demonstrate methods like add() and remove().Iterate through the set. Perform common set
operations like union, intersection, and difference.
# Sets
# Creation
# Using set literals
my_set = {1, 2, 3, 4, 5}
# Using the set() constructor
another_set = set(range(1, 6))
print("Created set:", my_set)
print("Another set:", another_set)
# Adding and Removing Elements
# Adding elements
my_set.add(6)
print("After add:", my_set)
# Removing elements
my_set.remove(3)
print("After remove:", my_set)
# Iteration
# Using for loop
print("Iterating using for loop:")
for item in my_set:
print(item)
# Set Operations
# Union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2)
print("Union set:", union_set)
# Intersection
intersection_set = [Link](set2)
print("Intersection set:", intersection_set)
# Difference
difference_set = [Link](set2)
print("Difference set:", difference_set)
Step:4 Working with Dictionary
Create a dictionary using different methods such as dictionary literals and the dict()
constructor. Demonstrate accessing elements by keys. Demonstrate methods like update()
and pop().Iterate through the dictionary using keys, values, and items.
# Dictionaries
# Creation
# Using dictionary literals
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Using the dict() constructor
another_dict = dict(name='Bob', age=25, city='Chicago')
print("Created dictionary:", my_dict)
print("Another dictionary:", another_dict)
# Accessing Elements
# By keys
print("Name:", my_dict['name'])
print("Age:", my_dict['age'])
# Adding and Removing Elements
# Adding elements
my_dict['email'] = 'alice@[Link]'
print("After adding email:", my_dict)
# Removing elements
removed_value = my_dict.pop('age')
print("Removed age:", removed_value)
print("After removing age:", my_dict)
# Iteration
# Using keys
print("Iterating keys:")
for key in my_dict:
print(key)
# Using values
print("Iterating values:")
for value in my_dict.values():
print(value)
# Using items
print("Iterating items:")
for key, value in my_dict.items():
print(key, ":", value)
# Use Case
# Contact book
contact_book = {
'Alice': {'phone': '123-456-7890', 'email': 'alice@[Link]'},
'Bob': {'phone': '987-654-3210', 'email': 'bob@[Link]'}
}
print("Contact book:", contact_book)
Lab: Working with Packages and Modules
Lab Objective: The objective of this lab is to guide participants through creating a Python
package with multiple modules using Visual Studio Code. By the end of this lab, participants
should be able to:
Create a Python package structure within Visual Studio Code.
Understand how to organize modules within a package.
Import modules from the package into a Python program.
Execute a sample program that utilizes functions or classes defined within the
package.
Lab Steps:
Step 1: Setting Up Visual Studio Code
Ensure that Visual Studio Code is installed on your system. You can download and install it
from the official website ([Link]
Step 2: Creating the Package Structure
Open Visual Studio Code.
Create a new folder for the package. Right-click in the Explorer pane and select "New
Folder". Name it my_package.
Inside the my_package folder, create another folder named subpackage.
Step 3: Creating Modules
Inside the my_package folder, right-click and select "New File". Create Python
modules with .py extension.
Example: [Link], [Link]
Define functions, classes, or variables within these modules.
Step 4: Organizing Modules within the Package
Drag and drop the modules created in Step 3 into the subpackage folder.
[Link] and [Link] should now be inside the subpackage folder.
Open each module file ([Link], [Link]) by double-clicking on them in the
Explorer pane.
Within each module, define functions, classes, or variables based on the requirements
of your package.
Example:
# [Link]
def greet(name):
return f"Hello, {name}!"
# [Link]
class Calculator:
def add(self, x, y):
return x + y
Step 5: Creating the __init__.py file
Inside the my_package folder, right-click and select "New File". Name it __init__.py.
This file can be left empty.
This step is necessary to treat the directory as a package.
Step 6: Using the Package in a Sample Program
Create a new Python file outside the my_package folder. Right-click and select "New
File". Name it [Link].
Import modules from the created package using the dot notation.
Example: from my_package.subpackage import module1, module2
Utilize functions or classes defined within these modules in your [Link] program as
shown in example below
# Using functions from module1
from my_package.subpackage import module1, module2
print([Link]("Alice")) # Output: Hello, Alice!
# Using classes from module2
calc = [Link]()
result = [Link](5, 3)
print("5 + 3 =", result) # Output: 5 + 3 = 8
Step 7: Running the Sample Program
Open the [Link] file.
Use the Visual Studio Code built-in terminal to navigate to the directory containing
[Link].
Execute the [Link] program using the Python interpreter.
Example: python [Link]
Ensure that the program executes without errors and produces the expected output.
Lab Conclusion: This lab has provided you with practical experience in organizing code into
packages and modules within the Visual Studio Code environment.
Lab:2 Working with Functions
The objective of this lab is to introduce learners to the basics of functions in Python,
covering topics such as return types, passing multiple arguments, passing multiple keyword
arguments, returning a function, and passing a function as an argument. By the end of this
lab, participants should be able to:
Understand the fundamentals of defining and calling functions in Python.
Learn how to work with different types of arguments and return values in functions.
Gain practical experience through hands-on exercises that cover various scenarios
involving functions.
Step 1: Defining and Calling Functions
Simple Function: Define a simple function that takes no arguments and prints a message
when called.
# Define a simple function that prints a message
def greet():
print("Hello! Welcome to the Python functions lab.")
# Call the function
greet()
Step 2: Return Types
Function with Return Value: Define a function that takes two numbers as arguments and
returns their sum.
# Define a function that returns the sum of two numbers
def add_numbers(x, y):
return x + y
# Call the function and store the result
result = add_numbers(3, 5)
print("Sum:", result)
Step 3: Passing Multiple Arguments
Function with Multiple Arguments: Define a function that takes multiple arguments and
calculates their product.
# Define a function that takes multiple arguments and calculates their product
def multiply(*args):
product = 1
for num in args:
product *= num
return product
# Call the function with multiple arguments
result = multiply(2, 3, 4)
print("Product:", result)
Step 4: Passing Multiple Keyword Arguments
Function with Keyword Arguments: Define a function that takes multiple keyword
arguments and prints their values.
# Define a function that takes multiple keyword arguments and prints their values
def print_info(**kwargs):
for key, value in [Link]():
print("{}: {}".format(key, value))
# Call the function with keyword arguments
print_info(name="Alice", age=30, city="New York")
Step 5: Returning a Function
Function Returning a Function: Define a function that returns another function, which
calculates the square of a number.
# Define a function that returns another function
def get_square_function():
def square(x):
return x ** 2
return square
# Get the square function and call it
square_function = get_square_function()
result = square_function(5)
print("Square:", result)
Explanation:
The get_square_function() function defines an inner function square() that calculates
the square of its input.
This inner function square() is then returned as the result of calling
get_square_function().
We store the returned function in the variable square_function.
Finally, we call square_function(5) to calculate the square of 5, which results in 25.
Step 6: Passing a Function as an Argument
Function Taking a Function as an Argument: Define a higher-order function that takes
another function as an argument and applies it to a list of values.
# Define a higher-order function that takes another function as an argument
def apply_function(func, values):
return [func(x) for x in values]
# Define a simple function to double a number
def double(x):
return x * 2
# Call the higher-order function with the double function
numbers = [1, 2, 3, 4, 5]
result = apply_function(double, numbers)
print("Result:", result)
conclusion:
Functions in Python are essential for organizing code and performing reusable tasks.
They can return values using the return statement and accept multiple arguments,
including variable-length arguments and keyword arguments.
Functions can also return other functions and accept functions as arguments,
enabling powerful programming paradigms like higher-order functions and functional
programming.
Lab: 3 Working with lambda Functions
The objective of this lab is to provide a comprehensive understanding of
lambda functions in Python, from simple to complex usage. Participants
will learn how to define and use lambda functions effectively for various
tasks. By the end of this lab, learners should be able to:
Understand the syntax and purpose of lambda functions.
Apply lambda functions for simple tasks, such as arithmetic
operations and filtering lists.
Use lambda functions in conjunction with built-in functions like map,
filter, and sorted.
Explore advanced usage of lambda functions, including sorting
complex data structures and functional programming paradigms.
What is lambda function?
Lambda functions, known as anonymous functions, are small, inline
functions defined using the lambda keyword. They are useful for short,
one-off operations where defining a regular function would be
cumbersome. Lambda functions have a simple syntax: lambda arguments:
expression.
Step 1: Simple Lambda Functions
Arithmetic Operation: Define a lambda function to perform a basic arithmetic
operation, such as addition or multiplication.
# Define a lambda function to perform addition
add = lambda x, y: x + y
# Test the lambda function
result = add(3, 5)
print("Result of addition:", result) # Output: 8
Step 2: Using Lambda Functions with Built-in Functions
Map Function: Use a lambda function with the map function to apply a
transformation to each element of a list.
# Use map function with lambda to square each element of a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared numbers:", squared_numbers)
Filter Function: Use a lambda function with the filter function to filter
elements from a list based on a condition.
# Use filter function with lambda to filter even numbers from a list
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
Sorted Function: Use a lambda function with the sorted function to sort a list
of numbers or strings.
# Use sorted function with lambda to sort a list of strings based on length
words = ['apple', 'banana', 'orange', 'strawberry', 'kiwi']
sorted_words = sorted(words, key=lambda x: len(x))
print("Sorted words by length:", sorted_words)
Step 3: Advanced Lambda Functions
Sorting Complex Data Structures: Use a lambda function to sort a list of
dictionaries or tuples based on a specific key.
# Define a list of tuples representing students and their scores
students = [('Alice', 85), ('Bob', 90), ('Charlie', 75)]
# Sort the list of tuples based on the second element (score)
sorted_students = sorted(students, key=lambda x: x[1], reverse=True)
print("Sorted students by score:", sorted_students)
Functional Programming Paradigms: Explore functional programming concepts
by applying lambda functions for data transformation and higher-order
functions.
# Define a higher-order function that applies a transformation to a list of
values
def apply_transformation(func, values):
return [func(x) for x in values]
# Use apply_transformation with a lambda function to double each
element
doubled_numbers = apply_transformation(lambda x: x * 2, numbers)
print("Doubled numbers:", doubled_numbers)
Lab Conclusion: In this lab, You have learned how to define lambda
functions for various tasks, apply them with built-in functions like map,
filter, and sorted, and explore advanced concepts such as sorting complex
data structures and functional programming paradigms. Lambda functions
are powerful tools for writing concise and expressive code in Python,
enabling you to perform a wide range of operations efficiently.
Important Note:
Lambda functions are powerful tools in Python for writing concise and
expressive code. They are commonly used for short, one-line operations
and are often employed with built-in functions like map, filter, and sorted.
Additionally, lambda functions facilitate functional programming
paradigms, allowing for more elegant and readable code. Understanding
lambda functions is essential for mastering Python programming and
enables you to tackle a wide range of tasks efficiently.
Lab:4 Working with functions and datetime
Lab Objective: The objective of this lab is to demonstrate the usage of the datetime module
in Python for date and time manipulation, particularly in the context of analytics. By the end
of this lab, participants should be able to:
Understand how to work with dates and times using the datetime module.
Filter data based on quarterly, monthly, and weekly frequencies.
Gain practical experience in extracting and manipulating date-related information for
analytics purposes.
Scenario: Analyzing Sales Data
You are tasked with analyzing sales data from a retail store. The sales data includes
information about transactions, such as the date of purchase and the amount sold. You need
to use the datetime module to filter the sales data based on quarterly, monthly, and weekly
frequencies for further analysis.
Step 1: Setting Up the Environment
Ensure that Python is installed on your system. You can download and install Python from
the official website ([Link]
Step 2: Importing the datetime Module
Open your preferred Python editor or IDE.
Import the datetime module at the beginning of your Python script.
import datetime
Step 3: Generating Sample Sales Data
Create sample sales data containing transaction dates and amounts.
You can use a list of dictionaries or any other suitable data structure to represent the
sales data.
sales_data = [
{"date": "2023-01-05", "amount": 100},
{"date": "2023-01-15", "amount": 150},
{"date": "2023-02-10", "amount": 200},
{"date": "2023-03-20", "amount": 250},
# Add more sales data as needed
]
Note: Here, we create a list of dictionaries called sales_data, where each dictionary
represents a sales transaction. Each transaction has two key-value pairs: "date" for the
transaction date (in the format "YYYY-MM-DD") and "amount" for the amount sold.
Step 4: Filtering Data Based on Quarterly Frequency
Define a function to filter sales data based on quarterly frequency.
Use the datetime module to parse the transaction dates and extract the quarter
information.
Filter the sales data based on the specified quarter.
def filter_quarterly_data(data, year, quarter):
quarterly_data = []
for entry in data:
transaction_date = [Link](entry["date"], "%Y-%m-%d")
if transaction_date.year == year and (transaction_date.month - 1) // 3 + 1 == quarter:
quarterly_data.append(entry)
return quarterly_data
# Example: Filter sales data for the first quarter of 2023
quarterly_sales_data = filter_quarterly_data(sales_data, 2023, 1)
print("Sales data for Q1 2023:", quarterly_sales_data)
Code Explanation: In this step, we define a function filter_quarterly_data that takes three
arguments: data (the list of sales transactions), year, and quarter. Inside the function, we
iterate over each transaction in the data list. We convert the transaction date string to a
datetime object using strptime, which parses a string representing a time according to a
specified format. Then, we compare the year and quarter of the transaction date with the
provided year and quarter. If they match, we add the transaction to the quarterly_data list.
Finally, we return the quarterly_data list containing transactions for the specified quarter.
We call this function to filter sales data for the first quarter of 2023 and store the result in
quarterly_sales_data. We then print the filtered sales data.
Step 5: Filtering Data Based on Monthly Frequency
Define a function to filter sales data based on monthly frequency.
Use the datetime module to parse the transaction dates and extract the month
information.
Filter the sales data based on the specified month.
def filter_monthly_data(data, year, month):
monthly_data = []
for entry in data:
transaction_date = [Link](entry["date"], "%Y-%m-%d")
if transaction_date.year == year and transaction_date.month == month:
monthly_data.append(entry)
return monthly_data
# Example: Filter sales data for January 2023
monthly_sales_data = filter_monthly_data(sales_data, 2023, 1)
print("Sales data for January 2023:", monthly_sales_data)
Code Explanation: Similar to filtering by quarter, here we define a function
filter_monthly_data to filter sales data based on a specified year and month. Inside the
function, we iterate over each transaction in the data list. We parse the transaction date
string to a datetime object and compare the year and month of the transaction date with
the provided year and month. If they match, we add the transaction to the monthly_data
list. Finally, we return the monthly_data list containing transactions for the specified month.
We call this function to filter sales data for January 2023 and store the result in
monthly_sales_data. We then print the filtered sales data.
Step 6: Filtering Data Based on Weekly Frequency
Define a function to filter sales data based on weekly frequency.
Use the datetime module to parse the transaction dates and calculate the week
number.
Filter the sales data based on the specified week.
def filter_weekly_data(data, year, week):
weekly_data = []
for entry in data:
transaction_date = [Link](entry["date"], "%Y-%m-%d")
if transaction_date.year == year and transaction_date.isocalendar()[1] == week:
weekly_data.append(entry)
return weekly_data
# Example: Filter sales data for the first week of 2023
weekly_sales_data = filter_weekly_data(sales_data, 2023, 1)
print("Sales data for the first week of 2023:", weekly_sales_data)
Code Explanation: Here, we define a function filter_weekly_data to filter sales data based on
a specified year and week number. Inside the function, we iterate over each transaction in
the data list. We parse the transaction date string to a datetime object and compare the year
and week number of the transaction date with the provided year and week. If they match,
we add the transaction to the weekly_data list. Finally, we return the weekly_data list
containing transactions for the specified week.
We call this function to filter sales data for the first week of 2023 and store the result in
weekly_sales_data. We then print the filtered sales data.
Lab:5 Working with Regular Expression
The objective of this lab is to introduce learners to regular expressions in Python and
demonstrate their usage for common tasks such as validating dates, emails, and phone
numbers, as well as transforming data using patterns defined by regular expressions. By the
end of this lab, participants should be able to:
Understand the basics of regular expressions and their syntax.
Apply regular expressions to validate and extract information from dates, emails, and
phone numbers.
Gain practical experience through hands-on exercises that involve transforming data
using regular expressions.
What is Regular Expression:
Regular expressions (regex) are sequences of characters that define a search pattern. They
are used to search, match, and manipulate text based on patterns. In Python, the re module
provides support for working with regular expressions.
Step 1 Basic Usage of Regular Expressions in Validations
Data Validation:
import re
# Define a regular expression pattern for date validation (YYYY-MM-DD)
date_pattern = r'^\d{4}-\d{2}-\d{2}$'
# Test the pattern with a date string
date = '2022-01-15'
if [Link](date_pattern, date):
print("Valid date:", date)
else:
print("Invalid date:", date)
Email Validation:
# Define a regular expression pattern for email validation
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Test the pattern with an email address
email = 'user@[Link]'
if [Link](email_pattern, email):
print("Valid email:", email)
else:
print("Invalid email:", email)
Phone Number validation:
# Define a regular expression pattern for phone number validation
phone_pattern = r'^\d{3}-\d{3}-\d{4}$'
# Test the pattern with a phone number
phone_number = '123-456-7890'
if [Link](phone_pattern, phone_number):
print("Valid phone number:", phone_number)
else:
print("Invalid phone number:", phone_number)
Step 2: Transformation Using Regular Expressions
Date Transformation:1
# Define a regular expression pattern for date transformation (YYYY-MM-DD to DD-MM-
YYYY)
date_transform_pattern = r'^(\d{4})-(\d{2})-(\d{2})$'
# Define a function to transform dates
def transform_date(date_str):
match = [Link](date_transform_pattern, date_str)
if match:
year, month, day = [Link]()
return f"{day}-{month}-{year}"
else:
return "Invalid date format"
# Test the transformation with a date string
date = '2022-01-15'
transformed_date = transform_date(date)
print("Transformed date:", transformed_date)
Date Transformation:2 String to date type
import re
from datetime import datetime
# Define a regular expression pattern for the input string format (YYYYMMDD)
input_pattern = r'^(\d{4})(\d{2})(\d{2})$'
# Define a function to transform string to date type
def transform_to_date(date_str):
match = [Link](input_pattern, date_str)
if match:
year, month, day = [Link]()
date = datetime(int(year), int(month), int(day))
return date
else:
return "Invalid input format"
# Test the transformation with a string
input_date_str = '20240304'
transformed_date = transform_to_date(input_date_str)
print("Transformed date:", transformed_date)
Step:3 Data Cleaning Using Regular Expressions
clean the prices by removing the dollar sign $ and converting them to floats.
import re
# Define a string with unclean data
unclean_data = "The price of the product is $20.50, but it's on sale for only $15.99!! Hurry
up!"
# Define a regular expression pattern to extract prices
price_pattern = r'\$\d+\.\d{2}'
# Use the findall method to extract prices from the unclean data
prices = [Link](price_pattern, unclean_data)
# Clean the prices by removing the dollar sign and converting them to floats
cleaned_prices = [float(price[1:]) for price in prices]
# Print the cleaned prices
print("Cleaned prices:", cleaned_prices)
Lab:06 Working with Random Module
The objective of this lab is to demonstrate the usage of the random module in Python and
create sample multidimensional data using a list of dictionaries. Participants will learn how
to generate random numbers, strings, and other data types using the random module, and
how to structure this data into a multidimensional format for further analysis. By the end of
this lab, learners should be able to:
Understand the basics of the random module and its functions.
Generate random data representing different data types.
Organize the generated data into a multidimensional format using a list of
dictionaries.
Step 1: Introduction to the Random Module
Understanding the Random Module:
The random module in Python provides functions for generating random numbers,
sequences, and data types. It is commonly used for tasks such as simulation, testing, and
generating sample data. Some of the key functions in the random module include
[Link](), [Link](), [Link](), and [Link](), among others.
Step 2: Generating Sample Data
Generating Random Numbers: Use the [Link]() function to generate random
integer numbers within a specified range.
import random
# Generate a random integer between 1 and 100
random_integer = [Link](1, 100)
print("Random Integer:", random_integer)
Generating Random Floating-Point Numbers: Use the [Link]() function to
generate random floating-point numbers within a specified range.
# Generate a random floating-point number between 0 and 1
random_float = [Link](0, 1)
print("Random Float:", random_float)
Generating Random Strings: Use the [Link]() function to generate random strings
by selecting characters from a given sequence.
# Define a sequence of characters
characters = 'abcdefghijklmnopqrstuvwxyz'
# Generate a random string of length 5
random_string = ''.join([Link](characters) for _ in range(5))
print("Random String:", random_string)
Generating Other Random Data Types: Demonstrate the generation of random data types
such as booleans and dates using appropriate functions from the random module.
# Generate a random boolean value
random_boolean = [Link]([True, False])
print("Random Boolean:", random_boolean)
# Generate a random date within a range (e.g., past 30 days)
import datetime
end_date = [Link]()
start_date = end_date - [Link](days=30)
random_date = start_date + [Link](days=[Link](0, 30))
print("Random Date:", random_date)
Step 3: Creating Multidimensional Data
Creating Sample Multidimensional Data: Organize the generated random data into a
multidimensional format using a list of dictionaries, where each dictionary represents a data
point with multiple attributes.
# Generate sample multidimensional data using a list of dictionaries
sample_data = []
# Define a sequence of characters
characters = 'abcdefghijklmnopqrstuvwxyz'
for _ in range(5):
data_point = {
'id': [Link](1, 1000),
'name': ''.join([Link](characters) for _ in range(5)),
'age': [Link](20, 40),
'score': [Link](0, 100)
}
sample_data.append(data_point)
# Print the sample multidimensional data
print("Sample Multidimensional Data:")
for data_point in sample_data:
print(data_point)
Step 4: Conclusion
Summary: Reflect on the key learnings from the lab and discuss the potential applications of
using random data generation and multidimensional data structures in real-world scenarios.
Lab:7 Read data from the CSV file and demonstrate how to
apply the transformation to data
Lab Objective: This lab demonstrates how to apply transformations on data in a CSV file, let's
create a sample CSV file with some data and then apply a transformation to convert the data
to uppercase.
Step 1 Create a CSV File: First, create a CSV file named [Link] and add some sample data to
it. You can use a text editor or spreadsheet software like Microsoft Excel or Google Sheets to
create and save the file. For example:
Name,Age,City
John,25,New York
Alice,30,San Francisco
Bob,35,Chicago
Save the file as [Link]
Step 2 Apply Transformation: Write a Python script to read the data from the CSV file, apply
the transformation (convert names to uppercase), and then save the transformed data back
to a new CSV file. Here's how you can do it:
import csv
# Function to apply transformation (convert names to uppercase)
def apply_transformation(data):
transformed_data = []
for row in data:
transformed_row = [row[0].upper(), row[1], row[2]] # Convert name to uppercase
transformed_data.append(transformed_row)
return transformed_data
# Read data from CSV file
with open('[Link]', mode='r') as file:
reader = [Link](file)
data = list(reader)
# Apply transformation
transformed_data = apply_transformation(data)
# Write transformed data to a new CSV file
with open('transformed_data.csv', mode='w', newline='') as file:
writer = [Link](file)
[Link](transformed_data)
print("Transformation applied successfully.")
Step 3 Run the Script: Save the Python script in the same directory as the [Link] file. Then,
run the script. It will read the data from [Link], apply the transformation (convert names
to uppercase), and save the transformed data to a new CSV file named
transformed_data.csv.
Step 4 Verify the Results: Open the transformed_data.csv file to verify that the
transformation has been applied successfully.