Assignmentt 3 of Python
Assignmentt 3 of Python
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):
# Example input
# Generate list of numbers from 1 to 100 that are divisible by both 3 and
5
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:
set1 = set(list1)
set2 = set(list2)
# Example input
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
Output:
def create_student_database():
student_db = {}
for _ in range(3):
student_db[name] = {
"age": age,
"grade": grade,
"city": city
return student_db
student_database = create_student_database()
# Print the resulting nested dictionary
print("\nStudent Database:")
print(student_database)
Output:
def input_tuples(n):
tuples_list = []
for i in range(n):
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):
n=5
tuples_list = input_tuples(n)
sorted_tuples = sort_by_second_element(tuples_list)
Output:
def count_frequencies(int_list):
frequency_dict = {}
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]
frequency_dict = count_frequencies(int_list)
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):
result = {}
if key in result:
result[key].append(value)
else:
result[key] = [value]
return result
# Example input
result_dict = convert_to_dict_of_lists(dict_list)
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):
# Unpack the tuples into separate lists for keys and values
# Example input
print("Zipped:", zipped_list)
Output: