Tuples and Dictionaries in Python
Tuples and Dictionaries in Python Tuples are immutable sequences, i.e., we cannot change the elements of a tuple once it is created. Elements of a tuple are put in round brackets separated by commas. If a sequence has comma separated elements without parentheses, it is also treated as a tuple. Tuples are ordered sequences as each element has a fixed position. Indexing is used to access the elements of the tuple; two way indexing holds in dictionaries as in strings and lists. Operator โ+โ adds one sequence (string, list, tuple) to the end of other. Operator โ*โ repeats a sequence (string, list, tuple) by specified number of times Membership operator โinโ tells if an element is present in the sequence or not and โnot inโ does the opposite. Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), max(),sum(). Dictionary is a mapping (non-scalar) data type. It is an unordered collection of key-value pair; key value pair are put inside curly braces. Each key is separated from its value by a colon. Keys are unique and act as the index. Keys are of immutable type but values can be mutable Tuples and Dictionaries in Python
Tuples and Dictionaries in Python
Q1. Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. print ( sorted ( tuple1 ) )
print(tuple1)
(23, 1, 45, 67, 45, 9, 55, 45)
Tuples and Dictionaries in Python
Q2. Consider the following dictionary stateCapital:
stateCapital = {“AndhraPradesh” : “Hyderabad” , “Bihar”:”Patna” , “Maharashtra” : “Mumbai” , “Rajasthan”:”Jaipur”}
Find the output of the following statements:
i. print(stateCapital.get(“Bihar”))
ii. print(stateCapital.keys())
iii. print(stateCapital.values())
iv. print(stateCapital.items())
v. print(len(stateCapital))
vi print(“Maharashtra” in stateCapital)
vii. print(stateCapital.get(“Assam”))
viii. del stateCapital[“AndhraPradesh”]
print(stateCapital)
NOTE : Part viii will return an error as there is a space between Andhra Pradesh in question and there is no such key in given dictionary. I removed the space and written output accordingly
Tuples and Dictionaries in Python
Q3. โLists and Tuples are orderedโ. Explain.
Q4. With the help of an example show how can you return more than one value from a function.
Ans. def multivalue(a, b, c): a = a + 2 b = b + 3 c = c + 4 return (a, b, c) p = 8 q = 9 r = 10 p, q, r = multivalue(p, q, r) print(p) print(q) print(r) OUTPUT: 10 12 14
Q5. What advantages do tuples have over lists?
1. Tuples are faster than list (due to their fixed size) 2. Tuples can be used as keys of dictionary. (due to their immutable nature) 3. Elements of tuples can not be deleted by mistake. ( due to their immutable nature )
Tuples and Dictionaries in Python
Q6. When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
A dictionary is used to store related values like employee id, employee name and salary. Here id will act as a key while name and salary act as value.
Q7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.
T1 = (1,2,3,4,5) When we execute the above code, the following error occurs which shows that we can not change the value of tuple. (since it is immutable) TypeError: ‘tuple’ object does not support item assignment So if we want to change the value of tuple we have to rebuilt it. Rebuilt means to assign the value again like T1 = (1, 2, 45, 4, 5)
T1[2] = 45
Tuples and Dictionaries in Python
Q8. TypeError occurs while statement 2 is running.
Give reason. How can it be corrected?
tuple1 = (5) #statement 1
len(tuple1) #statement 2
PROGRAMMING PROBLEMS
Tuples and Dictionaries in Python
Q1. Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email ids. Print all three tuples at the end of the
program. [Hint: You may use the function split()]
Ans. n=int(input("Enter how many email id to enter : ")) t1=() un = () dom = () for i in range(n): em = input("Enter email id : ") t1 = t1 + (em,) for i in t1: a = i.split('@') un = un + (a[0],) dom = dom + (a[1],) print("Original Email id's are : " , t1) print("Username are : " , un) print("Doman name are : " , dom) OUTPUT : Enter how many email id to enter : 2 Enter email id : csip@gmail.com Enter email id : bike@yahoo.com Original Email id's are : ('csip@gmail.com', 'bike@yahoo.com') Username are : ('csip', 'bike') Doman name are : ('gmail.com', 'yahoo.com')
Tuples and Dictionaries in Python
Q2. Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not.
We can accomplish these by:
(a) writing a user defined function
(b) using the built-in function
Ans. a) def searchname(t1,nm): for a in t1: if a == nm: print(nm , " Name is present in Tuple") return print("Name not found") n = int(input("How many names you want to enter : ")) name = () for i in range(n): nm = input("Enter name : ") name = name + (nm,) nm = input("Enter name to search : ") searchname(name, nm) OUTPUT How many names you want to enter : 3 Enter name : Amit Enter name : Anuj Enter name : Ashish Enter name to search : Anuj Anuj Name is present in Tuple Ans b) n = int(input("How many names you want to enter : ")) name = () for i in range(n): nm = input("Enter name : ") name = name + (nm,) nm = input("Enter name to search : ") if nm in name: print(nm," Name is present in Tuple") else: print(nm," Name is not present in Tuple") OUTPUT: How many names you want to enter : 3 Enter name : Amit Enter name : Anuj Enter name : Ashu Enter name to search : Ashu Ashu Name is present in Tuple
Tuples and Dictionaries in Python
Q3. Write a Python program to find the highest 2 values in a dictionary.
Ans. D = {'A' : 23, 'B' : 56, 'C' : 29, 'D' : 42, 'E' : 78 } val = [ ] v = D.values() for i in v: val.append(i) val.sort() print("Two maximum values are") print(val[-1]) print(val[-2]) OUTPUT: Two maximum values are 78 56
Tuples and Dictionaries in Python
Q4. Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : ‘w3resource’
Expected output : {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1,’e’: 2, ‘o’: 1}
Ans. str = input("Enter any String") D = { } for i in str: if i not in D: D[ i ] = str.count(i) print(D) OUTPUT : Enter any String : amitamit {'a' : 2, 'm' : 2, 'i' : 2, 't' : 2}
Tuples and Dictionaries in Python
Q5. Write a program to input your friendsโ names and their Phone Numbers and store them in the dictionary as the key-value pair.
Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
Tuples and Dictionaries in Python
Ans. friends = { } while True: print("1. Add New Contact") print("2. Display all ") print("3. Delete any contact") print("4. Modify/Change Phone Number") print("5. Check if a friend is present or not") print("6. Display in sorted order of names") print("7. Exit") ch = int(input("Enter your choice : ")) if ch == 1 : nm = input("Enter name : ") ph = input("Enter phone number : ") friends[ph] = nm print("Record Added") elif ch == 2 : for i in friends : print("Name : " , friends[i]) print("Contact number : ", i) elif ch == 3 : c = input("Enter the phone number to delete") if c in friends: del friends[c] else: print("No Record found") elif ch == 4: p = input("Enter the contact number to be modified") if p in friends: n = input("Enter the new name") friends[p] = n print("Record Modified") else: print("No Record Found") elif ch == 5: ph = input("Enter the contact number to check") if ph in friends: print("Record Present") else : print("Record not found") elif ch == 6: for i in sorted(friends.values()): print(i) elif ch == 7: break else: print("Enter Value between 0 and 7")
Tuples and Dictionaries in Python
Disclaimer : I tried to give you the correct “Tuples and Dictionaries in Python Chapter 10” , but if you feel that there is/are mistakes in the “Tuples and Dictionaries in Python Chapter 10 “ given above, you can directly contact me at csiplearninghub@gmail.com.
Tuples and Dictionaries in Python
Class 12 Computer Science Sample Paper 2020-2021.
Class 12 Computer Science Sample Paper Marking Scheme
Class 12 Computer Science Test Series








