Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Python Lab-Book Assignment 3

The document discusses tuples, sets and dictionaries in Python. It covers how to create, access and modify tuples and sets, as well as set operations like union, intersection and difference. Common tuple and set functions are also explained.

Uploaded by

Fatema Darekhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Lab-Book Assignment 3

The document discusses tuples, sets and dictionaries in Python. It covers how to create, access and modify tuples and sets, as well as set operations like union, intersection and difference. Common tuple and set functions are also explained.

Uploaded by

Fatema Darekhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Assignment 3: Working With Tuples, Sets and Dictionaries

Python Tuple:
A Tuple is a collection of Python objects separated by commas or written in round
brackets.
Ex >>>T1=“Hi”, “Hello”
>>>print(T1) #output: ( ‘Hi’, ‘Hello’)
>>>T2=(10,20,4.5,”Monday”)
>>>print(T2) #output: (10,20,4.5,’Mondy’)
Tuples are sequences, just like lists. The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
>>>print(T1[0]) #’Hi’
>>>print(T1[-1]) #’Hello’
>>>T1[0]=“Bye” #Error

Change Tuple Values:


Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable
For changing tuple values you can convert the tuple into a list, change the list, and convert
the list back into a tuple. Ex
>>>T1=(“Hi”, “Hello”) #Tuple T1
>>> T1[0]=“Bye” #Error
>>>T2=list(T1) #Converting Tuple T1 to list T2
>>>T2[0]=“Bye” #Updating List T2
>>>T1=tuple(T2) #Converting List T2 to tuple T1
>>>print(T1) #(‘Bye’, ‘Hello’)
The empty tuple is written as two parentheses containing nothing − >>> tup1 = ();
To write a tuple containing a single value you have to include a comma, even though
there is only one value - >>>tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
Different ways of accessing Tuple
>>>T1=(10,20,30,40)
>>>print(T1) #(10,20,30,40)
>>>print(T1[0]) #10
>>>for i in T1:
print(i,end= “ “) #10 20 30 40
>>>for i in range(len(T1)):
print(T1[i],end= “ “) #10 20 30 40
>>>print(“%f”%T1[0]) #10.000

Python Tuple Operator:


The concatenation (+) and repetition (*) operator work in the same way as they were
working with the strings.
Ex. >>>T1=(10,20,30);
>>>L2=(40,50)
>>>print(L1*2) #(10,20,30,10,20,30)
>>>print(L1+L2) #(10,20,30,40,50)
Membership operator in and not in can also be used to perform
operation on list Ex. >>>T1=[10,20,30]
>>> print (20 in T1) #True
>>>print (40 in T1) #False
>>>print(50 not in T1) #True
>>>print(30 not in T1) #False

Add Items:
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items:
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely: The del keyword can delete the tuple completely
Ex. >>>T1=(10,20)
>>>del T1
In-Built Tuple Functions:
1. cmp(): Python tuple method cmp() compares elements of two tuples.
syntax: cmp(tuple1, tuple2) cmp function return 0 if two tuples are same, 1 if
elements of first tuple is greater than elements of second tuple, otherwise -1
2. len(tuple): It is used to calculate the length of the tuple
>>>T1=(10,20,30)
>>>print(len(T1)) #3
3. max(Tuple): It returns the maximum element of the tuple.
4. min(Tuple): It returns the minimum element of the tuple.
>>>print(max(T1) #30
>>>print(min(T1)) #10
5. sum(tuple): Return sum of all elements within tuple
>>> print(sum(T1)) #60
6. all(tuple): it returns True if all the items in the tuple are true, otherwise it returns false.
If the tuple is empty, the function also returns true.
>>>T1=(10,20,30) T2=(10,0,20)
>>>print(all(T1)) #True
>>>print(all(T2)) #False
7. any(): Python any() function accepts iterable (list, tuple, dictionary etc.) as an
argument and return true if any of the element in iterable is true, else it returns false. If
iterable is empty then any() method returns false.
>>>print(any(T1)) #True
8. tuple(seq): It converts any sequence to the tuple.
>>>str=“Python”
>>>T1=tuple(str)
>>>print(T1) #(‘P’,’y’,’t’,’h’,’o’,’n’)
9. tuple.count(obj.): It returns the number of occurrences of the specified object in the
tuple. >>>L1=(10,20,40,10,20)
>>>print(L1.count(20)) #2
10. tuple.index(obj): It retuurns the lowest index in the tuple that object appears.
>>>T1=(10,20,30,20)
>>> print(T1.index(20)) #1
Packing and Unpacking:
In tuple packing, we place value into a new tuple while in tuple unpacking we extract
those values back into variables.
Ex >>> t=(101,”Nilesh”,80.78) #tuple packing
>>> (rollno, name, marks)=t #tuple unpacking
>>> print(rollno) # 101
>>>print(name, marks) #Nilesh 80.78

Python Set:
The set in python can be defined as the unordered collection of various items enclosed
within the curly braces. The elements of the set can not be duplicate. The elements of the
python set can not be changed.There is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print
them all together or we can get the list of elements by looping through the set.

Creating a set:
The set can be created by enclosing the comma separated items with the curly braces.
Python also provides the set method which can be used to create the set by the passed
sequence.

Creating set using curly brackets:


>>> city={"Pune", "Mumbai", "Nashik"}
>>> print(city) # {'Pune', 'Nashik', 'Mumbai'}
>>> for i in city:
print(i, end=“ “) # Pune Nashik Mumbai
Creating set using set() method:
>>> names=set([“Shubham”, “Nilesh”, “Pranav”])
>>>print(names) #{'Pranav', 'Shubham', 'Nilesh'}

Adding items to the set:


Python provides the add() method which can be used to add some particular item to the
set.
>>> names.add("Rajesh")
>>> print(names) #{'Pranav', 'Shubham', 'Rajesh', 'Nilesh'}
To add more than one item in the set, Python provides the update() method.
>>> print(city) #{'Pune', 'Nashik', 'Mumbai'}
>>> city.update(["Jalgaon","Nagpur","Satara"])
>>> print(city)
# {'Satara', 'Jalgaon', 'Pune', 'Mumbai', 'Nagpur', 'Nashik'}
Removing items from the set:
Python provides discard() method which can be used to remove the items from the set.
>>> city.discard("Mumbai")
>>> print(city) # {'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'} Python
also provide the remove() method to remove the items from the set.
>>> print(city) #{'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
>>> city.remove("Satara")
>>> print(city) #{'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
We can also use the pop() method to remove the item. However, this method will always
remove the first item.
>>> print(city) #{'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
>>> city.pop() #'Jalgaon‘
Python provides the clear() method to remove all the items from the set.
>>> print(city) #{'Nashik', 'Dhule'}
>>> city.clear()
>>> print(city) #set()

Difference between discard() and remove():


If the item to be deleted from the set using discard() doesn't exist in the set, the python
will not give the error.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the python will give the error.

Union of two Sets:


The union of two sets are calculated by using the or (|) operator. The union of the two sets
contains the all the items that are present in both the sets.
Ex. >>>s1={1,2,3}; s2={3,4,5}
>>>s3=s1|s3
>>>print(s3) #{1,2,3,4,5}
Python also provides the union() method which can also be used to calculate the union of
two sets.
>>> print(s1.union(s2)) #{1,2,3,4,5}

Intersection of two sets:


The & (intersection) operator is used to calculate the intersection of the two sets in
python.
The intersection of the two sets are given as the set of the elements that common in both
sets.
Ex >>> s1={"Pune","Mumbai","Jalgaon"}
>>> s2={"Nahik","Pune","Nagpur","Jalgaon"}
>>> s3=s1&s2
>>> print(s3) #{'Jalgaon', 'Pune'}
 using intersection() method
>>>s3=s1.intersection(s2)
>>>print(s3) #{'Jalgaon', 'Pune’}

The intersection_update() method:


The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
The Intersection_update() method is different from intersection() method since it modifies
the original set by removing the unwanted items, on the other hand, intersection() method
returns a new set.
Ex >>> a={1,2,3,4,5}
>>> b={3,5,7,8,9}
>>> a.intersection_update(b)
>>> print(a) #{3, 5}

Difference of two sets:


The difference of two sets can be calculated by using the subtraction (-) operator.
The resulting set consists of all the elements form set 1 which are not available in set2
Ex >>> a={1,2,3,4}
>>> b={3,5,4,8}
>>> c=a-b
>>> print(c) #{1, 2}
>>>print(b-a) #{5,8}
using difference() method
>>>print(a.difference(b)) #{1,2}

The difference_update():
The set difference_update() method modifies the existing set.
If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed,
then B gets modified into ( B – A).
Ex. >>>a={1,2,3,4,5}; b={3,4,5,6}
>>>a.difference_update(b)
>>>print(a) #{1,2}

The symmetric_difference():
This in-built function of Python Set helps us to get the symmetric difference between two
sets, which is equal to the elements present in either of the two sets, but not common to
both the sets. >>>print(a.symmetirc_difference(b)) #{1,2,6}

The symmetric_difference_update method:


symmetric_difference() method returns a new set which contains symmetric difference of
two sets. The symmetric_difference_update() method updates the set calling
symmetric_difference_update() with the symmetric difference of sets.
>>>a={1,2,3,4}; b={2,3,6,7}
>>>a.symmetric_difference_update(b)
>>>print(a) #{1,4,6,7}

issuperset() in Python:
The issuperset() method returns True if all elements of a set A occupies set B which is
passed as an argument and returns false if all elements of B not present in A.
This means if A is a superset of B then it returns true; else False
Syntax: A.issuperset(B) checks whether A is a superset of B or not. True if A is a superset
of B; otherwise false.
Ex >>>A={1,2,3,4,5}; B={2,3,4}
>>>A.issuperset(B)
#True >>>B.issuperset(A)
#False issubset() in python:
returns true if first set is a subset of seconds set otherwise false
>>> A.issubset(B) #False
>>>B.issubset(A) #True

isdisjoint() function in Python:


Two sets are said to be disjoint when their intersection is null.
In simple words they do not have any common element in between them.
Syntax: seta.isdisjoint(setb)
>>>a={1,2,3}; b={3,4,5}; c={7,8,9}
>>>a.isdisjoint(b) #False
>>>a.isdisjoint(c) #True
Set comparisons:
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by
using which we can check whether a set is subset, superset, or equivalent to other set.
The boolean True or False is returned depending upon the items present inside the sets.
Ex >>>a={1,2,3,4}; b={1,2,3}; c={1,2,3};
>>>print(a>b) #True
>>>print(a<b) #False
>>>print(b>a) #False
>>>print(a==b) #False
>>>print(b==c) #True
>>>print(a>=b) #True

Python Dictionary:
Dictionary in Python is an unordered collection of items in the form of key-value pair.
Dictionary holds key : value pair.
Each key-value pair in a Dictionary is separated by a colon :, whereas each item is
separated by a ‘comma’.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers
and tuples, but the values associated with key can be repeated and be of any type.
In Python, a Dictionary can be created by placing sequence of elements within curly {}
braces, separated by ‘comma’.
Ex >>> d={1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}
>>>print(d) #{1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}

Different ways of accessing dictionary


>>> d={“Rollno”:101, “Name”:“Nilesh”, “Marks”:80.75}
1. Printing whole dictionary using print() method :
>>>print(d)
{“Rollno”:101,“Name”:“Nilesh”, “Marks”: 80.75}
2. Accessing Individual value using index:
>>>print(d[“Name”]) #Nilesh
3. for loop to print all the keys of a dictionary >>>for x in d:
print(x, end=“ ”) # Name Rollno Marks
4. for loop to print all the values of the dictionary >>>for x in
d:
print(d[x],end= “ ”) # Nilesh 101 80.75
5. for loop to print the values of the dictionary by using values()
method >>> for i in d.values()
print(i, end=“ “) # Nilesh 101 80.75
6. for loop to print the items of the dictionary by using items()
method: >>> for in d.items()
print(i)
#output: (‘Name’, ‘Nilesh’)
(‘RollNo’,
101)
(‘Marks’, 80.75)
7. For loop to print key value pair:
>>> for k,v in d.items():
print(k,v)
#output: Name Nilesh

Rollno 101
Marks 80.75
8. Printing individual values of dictionary using format specifier:
>>> d={“Rollno”:101, “Name”:“Nilesh”, “Marks”:80.75}
>>> print("Roll No=%d"%d["Rollno"])
Roll No=101
>>> print("Name of student=
%s"%d["Name"]) Name of
student=Nilesh
>>> print("Marks Obtained=%f"%d["Marks"])
Marks Obtained=80.750000
Dictionary can also be created by the built-in function dict(). An empty dictionary can be
created by just placing to curly braces{}.
>>>D={ } # empty dictionary
>>>D=dict({1:”Hi”,2:”Hello”})
>>>print(D) #{1:”Hi”,2:”Hello”}
Note – Dictionary keys are case sensitive, same name but different cases of Key
will be treated distinctly.

Updating Dictionary:
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
Ex. >>> d={1: “One”, 2: “Two”}
>>>print(d) #{1: 'One', 2: 'Two‘}
>>>d[2]=“Twelve”
>>>print(d) #{1: 'One', 2: 'Tweleve'}
>>>d[3]=“Three”
>>>print(d) #{1: 'One', 2: 'Tweleve', 3: 'Three'}

Delete Dictionary Elements:


You can either remove individual dictionary elements or clear the entire contents of
a dictionary. You can also delete entire dictionary in a single operation.
Ex. >>> del d[2]
>>> print(d) #{1: 'One', 3: 'Three'}
Removing all elements for dictionary
>>> print(d) #{1: 'One', 3: 'Three'}
>>>d.clear() # remove all entries in dict
>>>print(d) #{ }
>>>del d # delete entire dictionary
>>>print(d) #Error

Properties of Dictionary:
1. In the dictionary, we can not store multiple values for the same keys.
If we pass more than one values for a single key, then the value which is last
assigned is considered as the value of the key.
>>>d={"RN":101,"Name":"Suresh","Marks":80,"Name":"Rajesh"}
>>> print(d) #{'Name': 'Rajesh', 'RN': 101, 'Marks': 80}
2. In python, the key cannot be any mutable object.
We can use numbers, strings, or tuple as the key but we can not use any mutable
object like the list as the key in the dictionary.
3. Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.

Built-in Dictionary functions:


1. len(): It is used to calculate the length of the dictionary.
Ex >>>d={1: “One”, 2: “Two”}
>>>print(len(d)) #2
2. str(dict.): It converts the dictionary into the printable string
>>>s=print(str(d))
>>>print(s) #{1: ‘One', 2: 'Two'}
>>>type(s) # <class 'str'>
3. copy(): It returns a shallow copy of the dictionary. Ex >>>d1={1: “One”, 2:
“Two”}
>>> d2=d1.copy()
>>>print(d2) #{1: “One”, 2: “Two”}
4. keys(): It returns all the keys of the dictionary.
>>> L=list(d1.keys())
>>>print(L) #[1, 2]
5. values(): It returns all the values of the dictionary.
>>>L=list(d1.values())
>>>print(L) #['One', 'Two']
6. popitem(): It remove and returns first item of the dictionary
>>> print(d1.popitem()) #(1: “One”)
>>> print(d1) #{2: “Two”}
7. pop(key): This method removes the specified item from the dictionary and return
the value of specified key.
>>>x=d1.pop(1)
>>>print(x) # One
8. Update(): The update() method inserts the specified items to the dictionary.
Ex >>>print(d)
{'Name': 'Shubham', 'RollNo': 101, 'Marks': 80}
>>> d.update({"Address":"Pimpri"})
>>> print(d)
{'Address': 'Pimpri', 'Name': 'Shubham', 'RollNo': 101, 'Marks': 80}

Assignments:
Practice Set:
1. Write a Python program to add and remove operation on set.
2. Write a Python program to do iteration over sets.
3. Write a Python program to find the length of a set.
4. Write a Python program to create a tuple with numbers and print one item.
5. Write a Python script to add a key to a dictionary. Sample Dictionary : {0: 10, 1:
20}
Expected Result : {0: 10, 1: 20, 2: 30}
Set A:

1. Write a Python program to find maximum and the minimum value in a set.
# Create a set
my_set = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}

# Find the maximum value in the set


max_value = max(my_set)

# Find the minimum value in the set


min_value = min(my_set)

# Print the results


print("Maximum value in the set:", max_value)
print("Minimum value in the set:", min_value)
Output:
Maximum value in the set: 9
Minimum value in the set: 1

2. Write a Python program to add an item in a tuple.


# Original tuple
my_tuple = (1, 2, 3, 4, 5)

# Item to add
item_to_add = 6

# Create a new tuple by concatenating the original tuple with a new tuple
containing the item
new_tuple = my_tuple + (item_to_add,)

# Print the new tuple


print("Original Tuple:", my_tuple)
print("New Tuple with Added Item:", new_tuple)
Output:
Original Tuple: (1, 2, 3, 4, 5)
New Tuple with Added Item: (1, 2, 3, 4, 5, 6)

3. Write a Python program to convert a tuple to a string.


# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Convert each element of the tuple to a string using a list comprehension


tuple_as_strings = [str(item) for item in my_tuple]

# Join the string representations of the tuple elements into a single string
result_string = ''.join(tuple_as_strings)

# Print the resulting string


print("Tuple as String:", result_string)
Output:
Tuple as String: 12345

4. Write a Python program to create an intersection of sets.


# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Find the intersection using the intersection() method


intersection_result = set1.intersection(set2)

# Print the intersection


print("Intersection of set1 and set2:", intersection_result)
Output:
Intersection of set1 and set2: {3, 4, 5}

5. Write a Python program to create a union of sets.


# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Find the union using the union() method


union_result = set1.union(set2)

# Print the union


print("Union of set1 and set2:", union_result)
Output:
Union of set1 and set2: {1, 2, 3, 4, 5, 6, 7}

6. Write a Python script to check if a given key already exists in a dictionary.


# Sample dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Key to check
key_to_check = 'age'

# Using the 'in' keyword


if key_to_check in my_dict:
print(f"'{key_to_check}' exists in the dictionary. Its value is:
{my_dict[key_to_check]}")
else:
print(f"'{key_to_check}' does not exist in the dictionary.")

# Using the 'get()' method


value = my_dict.get(key_to_check)
if value is not None:
print(f"'{key_to_check}' exists in the dictionary. Its value is: {value}")
else:
print(f"'{key_to_check}' does not exist in the dictionary.")
Output:
'age' exists in the dictionary. Its value is: 30
'age' exists in the dictionary. Its value is: 30

7. Write a Python script to sort (ascending and descending) a dictionary by value.

# Sample dictionary

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}

# Sort the dictionary by values in ascending order

sorted_dict_asc = dict(sorted(my_dict.items(), key=lambda item: item[1]))


# Print the sorted dictionary in ascending order

print("Sorted Dictionary (Ascending):", sorted_dict_asc)

# Sort the dictionary by values in descending order

sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1],


reverse=True))

# Print the sorted dictionary in descending order

print("Sorted Dictionary (Descending):", sorted_dict_desc)

Output:

Sorted Dictionary (Ascending): {'banana': 1, 'cherry': 2, 'apple': 3, 'date': 4}

Sorted Dictionary (Descending): {'date': 4, 'apple': 3, 'cherry': 2, 'banana': 1}

Set B:
1. Write a Python program to create set difference and a symmetric difference.
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Find the set difference (elements in set1 but not in set2) using the difference()
method
difference_result = set1.difference(set2)

# Find the symmetric difference (elements in either set1 or set2, but not in both)
using the symmetric_difference() method
symmetric_difference_result = set1.symmetric_difference(set2)

# Print the results


print("Set Difference (set1 - set2):", difference_result)
print("Symmetric Difference (set1 ^ set2):", symmetric_difference_result)
Output:
Set Difference (set1 - set2): {1, 2}
Symmetric Difference (set1 ^ set2): {1, 2, 6, 7}

2. Write a Python program to create a list of tuples with the first element as the
number and second element as the square of the number.
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Create a list of tuples where the first element is the number and the second
element is its square
result = [(num, num ** 2) for num in numbers]

# Print the list of tuples


print(result)
Output:
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

3. Write a Python program to unpack a tuple in several variables.


# Create a tuple
my_tuple = (1, 2, 3)

# Unpack the tuple into separate variables


var1, var2, var3 = my_tuple

# Print the unpacked variables


print("var1:", var1)
print("var2:", var2)
print("var3:", var3)
Output:
var1: 1
var2: 2
var3: 3

4. Write a Python program to get the 4th element from front and 4th element from
last of a tuple.
# Create a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Get the 4th element from the front (index 3)


fourth_from_front = my_tuple[3]

# Get the 4th element from the end (index -4)


fourth_from_end = my_tuple[-4]

# Print the results


print("4th Element from Front:", fourth_from_front)
print("4th Element from End:", fourth_from_end)
Output:
4th Element from Front: 4
4th Element from End: 7
5. Write a Python program to find the repeated items of a tuple.
# Sample tuple
my_tuple = (1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8)

# Create a dictionary to store item counts


item_counts = {}

# Find repeated items in the tuple


repeated_items = []

# Iterate through the tuple


for item in my_tuple:
# If the item is not in the dictionary, add it with a count of 1
if item not in item_counts:
item_counts[item] = 1
else:
# If the item is already in the dictionary, increment its count
item_counts[item] += 1

# Iterate through the dictionary to find repeated items


for item, count in item_counts.items():
if count > 1:
repeated_items.append(item)

# Print the repeated items


print("Repeated Items:", repeated_items)
Output:
Repeated Items: [2, 4, 6, 8]

6. Write a Python program to check whether an element exists within a tuple.


# Sample tuple
my_tuple = (1, 2, 3, 4, 5)

# Element to check
element_to_check = 3

# Check if the element exists in the tuple using the 'in' keyword
if element_to_check in my_tuple:
print(f"{element_to_check} exists in the tuple.")
else:
print(f"{element_to_check} does not exist in the tuple.")
Output:
3 exists in the tuple.

7. Write a Python script to concatenate following dictionaries to create a new one.


Sample
Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40}
dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3:
30, 4: 40, 5: 50, 6: 60}

# Sample dictionaries

dic1 = {1: 10, 2: 20}

dic2 = {3: 30, 4: 40}

dic3 = {5: 50, 6: 60}

# Method 1: Using the 'update()' method

result_dict = dic1.copy() # Make a copy of the first dictionary


to avoid modifying it

result_dict.update(dic2)

result_dict.update(dic3)

# Method 2: Using the '{**d1, **d2}' syntax

result_dict2 = {**dic1, **dic2, **dic3}

# Print the concatenated dictionary

print("Concatenated Dictionary (Method 1):", result_dict)

print("Concatenated Dictionary (Method 2):", result_dict2)

Output:

Concatenated Dictionary (Method 1): {1: 10, 2: 20, 3: 30, 4:


40, 5: 50, 6: 60}

Concatenated Dictionary (Method 2): {1: 10, 2: 20, 3: 30, 4:


40, 5: 50, 6: 60}
Set C:
1. Write a Python program to create a shallow copy of sets.
# Create a set
original_set = {1, 2, 3, 4, 5}

# Method 1: Using the 'copy()' method


shallow_copy1 = original_set.copy()

# Method 2: Using the 'set()' constructor


shallow_copy2 = set(original_set)

# Add an element to the original set to demonstrate that the copies are
shallow
original_set.add(6)

# Print the original set and the shallow copies


print("Original Set:", original_set)
print("Shallow Copy 1:", shallow_copy1)
print("Shallow Copy 2:", shallow_copy2)
Output:
Original Set: {1, 2, 3, 4, 5, 6}
Shallow Copy 1: {1, 2, 3, 4, 5}
Shallow Copy 2: {1, 2, 3, 4, 5}

2. Write a Python program to combine two dictionary adding values for


common keys. d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200,
'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})

from collections import Counter

# Input dictionaries
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}

# Combine the dictionaries using Counter


result = Counter(d1) + Counter(d2)

# Print the combined dictionary


print("Combined Dictionary:", result)
Output:
Combined Dictionary: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Need Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

You might also like