Python Programming Lab (CSA524)
Assignment 3
❖ Write a program that takes a dictionary with integer values
and returns a sorted dictionary by values. Then, create a
reversed sorted dictionary and print both versions.
o Example Input: {'a': 10, 'b': 5, 'c': 7}
o Expected Output: Sorted dictionary: {'b': 5, 'c': 7, 'a': 10},
Reversed sorted dictionary: {'a': 10, 'c': 7, 'b': 5}
Program:
def sort_dict_by_values(input_dict):
# Sort the dictionary by values in ascending order
sorted_dict = dict(sorted(input_dict.items(), key=lambda item: item[1]))
# Sort the dictionary by values in descending order
reversed_sorted_dict = dict(sorted(input_dict.items(), key=lambda
item: item[1], reverse=True))
return sorted_dict, reversed_sorted_dict
# Example input
input_dict = {'a': 10, 'b': 5, 'c': 7}
# Get sorted and reversed sorted dictionaries
sorted_dict, reversed_sorted_dict = sort_dict_by_values(input_dict)
# Print the results
print("Sorted dictionary:", sorted_dict)
print("Reversed sorted dictionary:", reversed_sorted_dict)
Output:
❖ Write a program to generate a list of numbers from 1 to 100
that are divisible by both 3 and 5 using list comprehension.
o Expected Output: [15, 30, 45, 60, 75, 90]
Program:
# Generate list of numbers from 1 to 100 that are divisible by both 3 and
5
divisible_by_3_and_5 = [num for num in range(1, 101) if num % 3 == 0
and num % 5 == 0]
# Print the result
print(divisible_by_3_and_5)
Output:
❖ Create a program to find the union, intersection, difference,
and symmetric difference of two sets. Take two lists as input
and convert them into sets for the operations.
o Example Input: List1 = [1, 2, 3, 4], List2 = [3, 4, 5, 6]
o Expected Output: Union = {1, 2, 3, 4, 5, 6}, Intersection =
{3, 4}, Difference (List1 - List2) = {1, 2}, Symmetric Difference
= {1, 2, 5, 6}
Program:
def set_operations(list1, list2):
# Convert lists to sets
set1 = set(list1)
set2 = set(list2)
# Perform set operations
union = set1 | set2
intersection = set1 & set2
difference = set1 - set2
symmetric_difference = set1 ^ set2
return union, intersection, difference, symmetric_difference
# Example input
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# Perform operations and get results
union, intersection, difference, symmetric_difference =
set_operations(list1, list2)
# Print the results
print("Union =", union)
print("Intersection =", intersection)
print("Difference (List1 - List2) =", difference)
print("Symmetric Difference =", symmetric_difference)
Output:
❖ Write a program to create a nested dictionary representing a
student database. The dictionary should have student names
as keys and each value should be another dictionary containing
student details like age, grade, and city. Allow users to input
details for at least 3 students and print the dictionary.
o Example Input: {"Alice": {"age": 21, "grade": "A", "city": "New
York"}, "Bob": {"age": 22, "grade": "B", "city": "Los Angeles"}}
Program:
# Function to create the student database
def create_student_database():
# Initialize an empty dictionary
student_db = {}
# Prompt the user to input details for 3 students
for _ in range(3):
name = input("Enter student name: ")
age = int(input(f"Enter age for {name}: "))
grade = input(f"Enter grade for {name}: ")
city = input(f"Enter city for {name}: ")
# Add details to the dictionary
student_db[name] = {
"age": age,
"grade": grade,
"city": city
return student_db
# Create the student database
student_database = create_student_database()
# Print the resulting nested dictionary
print("\nStudent Database:")
print(student_database)
Output:
❖ Write a program to sort a list of tuples based on the second
element of each tuple. Allow the user to input at least 5 tuples.
o Example Input: [(1, 2), (3, 1), (5, 7), (4, 4)]
o Expected Output: [(3, 1), (1, 2), (4, 4), (5, 7)]
Program:
# Function to input tuples from the user
def input_tuples(n):
tuples_list = []
for i in range(n):
print(f"Enter tuple {i+1} (format: x,y):")
x, y = map(int, input().split(','))
tuples_list.append((x, y))
return tuples_list
# Function to sort the list of tuples based on the second element
def sort_by_second_element(tuples_list):
return sorted(tuples_list, key=lambda x: x[1])
# Input at least 5 tuples from the user
n=5
tuples_list = input_tuples(n)
# Sort the list of tuples
sorted_tuples = sort_by_second_element(tuples_list)
# Print the result
print("Sorted list of tuples:", sorted_tuples)
Output:
❖ Write a program that takes a list of integers as input and
returns a dictionary with each unique integer as the key and its
frequency as the value.
o Example Input: [1, 2, 2, 3, 3, 3, 4]
o Expected Output: {1: 1, 2: 2, 3: 3, 4: 1}
Program:
def count_frequencies(int_list):
# Initialize an empty dictionary
frequency_dict = {}
# Count the frequency of each integer
for num in int_list:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1
return frequency_dict
# Example input
int_list = [1, 2, 2, 3, 3, 3, 4]
# Get the frequency dictionary
frequency_dict = count_frequencies(int_list)
# Print the result
print("Frequency dictionary:", frequency_dict)
Output:
❖ Write a program that takes a list of dictionaries and converts
it to a dictionary of lists.
o Example Input: [{"name": "Alice", "age": 21}, {"name":
"Bob", "age": 22}]
o Expected Output: {"name": ["Alice", "Bob"], "age": [21, 22]}
Program:
def convert_to_dict_of_lists(dict_list):
# Initialize an empty dictionary to store the result
result = {}
# Iterate over each dictionary in the list
for item in dict_list:
for key, value in item.items():
# Add values to the corresponding key in the result dictionary
if key in result:
result[key].append(value)
else:
result[key] = [value]
return result
# Example input
dict_list = [{"name": "Alice", "age": 21}, {"name": "Bob", "age": 22}]
# Convert to dictionary of lists
result_dict = convert_to_dict_of_lists(dict_list)
# Print the result
print("Dictionary of lists:", result_dict)
Output:
❖ Write a program to zip two lists into a list of tuples and then
unpack the tuples into separate lists for keys and values.
o Example Input: List1 = ["name", "age"], List2 = ["Alice", 21]
o Expected Output: Zipped: [("name", "Alice"), ("age", 21)],
Unpacked Keys: ["name", "age"], Unpacked Values: ["Alice", 21]
Program:
def zip_and_unpack(list1, list2):
# Zip the two lists into a list of tuples
zipped_list = list(zip(list1, list2))
# Unpack the tuples into separate lists for keys and values
keys, values = zip(*zipped_list)
return zipped_list, list(keys), list(values)
# Example input
list1 = ["name", "age"]
list2 = ["Alice", 21]
# Zip and unpack the lists
zipped_list, keys, values = zip_and_unpack(list1, list2)
# Print the results
print("Zipped:", zipped_list)
print("Unpacked Keys:", keys)
print("Unpacked Values:", values)
Output: