Chapter 10 Tuple & Dictionary Notes.
Chapter 10 Tuple & Dictionary Notes.
➢ TUPLE: Tuple is a collection of elements which are ordered and unchangeable (Immutable).
Immutable means you cannot change elements of a tuple in place.
BASICS OF TUPLE:
▪ Allows duplicate members.
▪ Consists of the values of any type, separated by comma.
▪ Tuples are enclosed within parentheses ( ).
▪ Cannot remove the element from a tuple.
Creating Tuple:
Syntax:
tuple-name = ( ) # empty tuple
tuple-name = (value-1, value-2, ..................... , value-n)
Example:
>>> T=(23, 7.8, 64.6, 'h', 'say')
>>> T
OUTPUT: (23, 7.8, 64.6, 'h', 'say')
>>> T=1,2,3 #A sequence without parenthesis is treated as tuple
>>>type(seq)
OUTPUT: <class ‘tuple’>
>>> print(seq)
OUTPUT: (1,2,3)
Creating a tuple with single element: Single element in tuple should be followed by comma, if the assigning
of single element is without comma, it is treated as an integer instead of tuple.
Example:
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T3
OUTPUT: 3
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T(3,)
OUTPUT: (3,)
>>> T1=3, # It also creates a tuple with single element
>>> T1(3,)
OUTPUT: (3,)
Creating a tuple using tuple( ) constructor:
o It is also possible to use the tuple( ) constructor to create a tuple.
>>>T=tuple( ) # empty tuple
>>> T=tuple((45,3.9, 'k',22)) #note the double round-brackets
>>> T
OUTPUT: (45, 3.9, 'k', 22)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
OUTPUT: ('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
OUTPUT: ('hello', 'python')
1
Nested Tuples: A tuple inside another tuple is called nested tuple.
>>> T=(5,10,(4,8))
>>> T
OUTPUT: (5, 10, (4, 8))
Creating a tuple by taking input from the user:
>>> T=tuple(input("enter the elements: "))enter
the elements: hello python
>>> T
OUTPUT: ('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1=tuple(input("enter the elements: "))
enter the elements: 45678
>>> T1
OUTPUT: ('4', '5', '6', '7', '8')
# it treats elements as the characters though we entered digits.
To overcome the above problem, we can use eval( ) method, which identifies the data type
and evaluates them automatically.
>>> T1=eval(input("enter the elements: "))
enter the elements: 56789
>>> T1
OUTPUT: 56789 # it is not a list, it is an integer value
>>> type(T1)
<class 'int'>
>>> T2=eval(input("enter the elements: "))
enter the elements: (1,2,3,4,5) # Parenthesis is optional
>>> T2
OUTPUT: (1, 2, 3, 4, 5)
>>> T3=eval(input("enter the elements: "))
enter the elements: 6, 7, 3, 23, [45,11] # list as an element of tuple
>>> T3
OUTPUT: (6, 7, 3, 23, [45, 11])
Accessing Tuples:
Tuples are very much similar to lists. Like lists, tuple elements are also [Link] indexing
as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
➢ The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) withindexes.
➢ tuple-name[start:end] will give you elements between indices start to end-1.
➢ The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
2
>>> alpha[46]
OUTPUT: IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain unchanged
OUTPUT: TypeError: 'tuple' object does not support item assignment
Difference between List and Tuple:
S. No. List Tuple
1 Ordered and changeable (Mutable) Ordered but unchangeable (Immutable)
2 Lists are enclosed in brackets. [ ] Tuples are enclosed in parentheses. ( )
3 Element can be removed. Element can’t be removed.
Traversing a Tuple:Syntax:
for <variable> in tuple-name:
statement
Example:
Method-1 OUTPUT:
>>> alpha=('q','w','e','r','t','y') q
>>> for i in alpha: w
print(i) e
r
Method-2 t
>>> for i in range(0, len(alpha)): y
print(alpha[i])
Tuple Operations:
➢ Joining operator +
➢ Repetition operator *
➢ Slice operator [:]
➢ Comparison Operator <, <=, >, >=, ==, !=
• Joining Operator: It joins two or more tuples.
Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
OUTPUT: (25, 50, 75, 5, 10, 15)
>>> T1 + (34)
OUTPUT: TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
OUTPUT: (25, 50, 75, 34)
Repetition Operator: It replicates a tuple, specified number of times.
Example:
>>> T1*2
OUTPUT: (25, 50, 75, 25, 50, 75)
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
OUTPUT:(30, 40, 30, 40, 30, 40)
• Slice Operator:
tuple-name[start:end] will give you elements between indices start to end-1.
3
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3]
OUTPUT: ('w', 'e')
>>> alpha[3:65]
OUTPUT: ('r', 't', 'y')
>>> alpha[-1:-5]
OUTPUT: ( )
>>> alpha[-5:-1]
OUTPUT: ('w', 'e', 'r', 't')
List-name[start:end:step] will give you elements between indices start to end-1 withskipping
elements as per the value of step.
>>> alpha[Link]
OUTPUT: ('w', 'r')
>>> alpha[ : : -1]
OUTPUT:('y', 't', 'r', 'e', 'w', 'q') #reverses the tuple
• Comparison Operators:
o Compare two tuples
o Python internally compares individual elements of tuples in lexicographical order.
o It compares each corresponding element must compare equal and two sequences must be
of the same type.
o For non-equal comparison as soon as it gets a result in terms of True/False, from
corresponding elements’ comparison. If Corresponding elements are equal, it goes to the
next element and so on, until it finds elements that differ.
Example:
>>> T1 = (9, 16, 7)
>>> T2 = (9, 16, 7)
>>> T3 = ('9','16','7')
>>> T1 = = T2
OUTPUT: True
>>> T1==T3
OUTPUT: False
>>> T4 = (9.0, 16.0, 7.0)
>>> T1==T4
OUTPUT: True
>>> T1<T2
OUTPUT: False
>>> T1<=T2
OUTPUT: True
Tuple Methods:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function Description Example
No. Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths",
Syntax: "Physics”)
len (tuple-name) >>> len(subject)
OUTPUT: 4
4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. OUTPUT: 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an errorbecause
mixed data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> max(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
Error: If the tuple contains values of different data types, then it will give an errorbecause
mixed data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> min(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
OUTPUT: NameError: name 'T' is not defined
DICTIONARY
Dictionary INTRODUCTION:
▪ A Dictionary is a collection of elements which are unordered, changeable and indexed.
▪ Dictionary has keys and values.
▪ Dictionaries are indexed by Keys not by Numbers. i.e. Doesn’t have index for values. Keys work as
indexes.
▪ Key must be unique. Dictionary doesn’t have duplicate member means no duplicate key.
▪ Dictionaries are enclosed by curly braces { }
▪ The key-value pairs are separated by commas ( , )
▪ A dictionary key can be almost any Python type but are usually numbers or strings.
▪ Values can be assigned and accessed using square brackets [ ].
CHARACTERISTICS OF A DICTIONARY
▪ Unordered set: A dictionary is a unordered set of key:value pair
▪ Not a sequence: Unlike a string, tuple, and list, a dictionary is not a sequence because it is unordered set of
elements. The sequences are indexed by a range of ordinal numbers. Hence, they are ordered but a dictionary
is an unordered collection.
▪ Indexed by Keys, Not Numbers: Dictionaries are indexed by keys. Keys are immutable type
▪ Keys must be unique: Each key within dictionary must be unique. However, two unique keys can have same
values.
Example: Data = {1:100, 2:200,3:300,4:200}
▪ Mutable: Like lists, dictionary are also mutable. We can change the value of a certain “key” in place
Example: >>> Data[3]=400
6
So, to change value of dictionary the format is :
DictionaryName[“key” / key ]=new_value
You can even add new key:value pair using the same format:
DictionaryName[“key” / key ]=new_value
CREATING A DICTIONARY:
Syntax:
dictionary-name = {key1:value, key2:value, key3:value, keyn:value}
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> D = { } #Empty dictionary
>>> D
OUTPUT: { }
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
OUTPUT: {'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that#
elements in dictionary can be accessed as per specific order.
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
OUTPUT: TypeError: unhashable type: 'list'
Creating a dictionary using dict( ) Constructor:
A. use the dict( ) constructor with single parentheses:
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
OUTPUT: {'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
➢ In the above case the keys are not enclosed in quotes and equal sign is usedfor assignment rather
than colon.
B. dict ( ) constructor using parentheses and curly braces:
>>> marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})
>>> marks
OUTPUT: {'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
7
Example: -b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
# tuple as argument passed to dict( ) constructor contains list type elements
>>> marks
OUTPUT: {'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
Example: -c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
# tuple as argument to dict( ) constructor and contains tuple type elements
>>> marks
OUTPUT: {'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
ACCESSING ELEMENTS OF A DICTIONARY:
Syntax:
dictionary-name[key]
Examples:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks["Maths"]
OUTPUT: 81
>>> marks["English"] #Access a key that doesn’t exist causes an error
OUTPUT: KeyError: 'English'
10
>>> 78 in marks # in and not in only checks the existence of keys not values
OUTPUT: False
However, if you need to search for a value in dictionary, then you can use in operatorwith the
following syntax:
Syntax:
value in dictionary-name. values( )
Examples:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 78 in [Link]( )
OUTPUT: True
DICTIONARY FUNCTIONS:
Consider a dictionary marks as follows:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
[Link]. Function Description Example
Name
1 len( ) Find the length of a >>> len(marks)
dictionary. OUTPUT: 4
Syntax:
len (dictionary-name)
2 clear( ) Removes all elements >>> [Link]( )
from the dictionary >>> marks
Syntax: OUTPUT: { }
[Link]( )
3 dict() Creates a dictionary from a >>>pair1 = [('Mohan',95),('Ram',89),
sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
OUTPUT: [('Mohan', 95), ('Ram', 89), ('Suhel',
92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
OUTPUT: {'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}
4 fromkeys() Return new dictionary with the >>>seq = ('name', 'age',’place’)
given set of elements as the >>>dict = [Link](seq)
keys of the dictionary. >>>print ("New Dictionary : “ , str(dict) )
Syntax: OUTPUT: New Dictionary : {'age': None, 'name':
[Link](keys, value) None, ’place’: None}
Note: >>>dict = [Link](seq, 10)
Set of elements should be >>>print ("New Dictionary : " , str(dict) )
immutable type. OUTPUT: New Dictionary : {'age': 10, 'name':
10, ’place’: 10}
5 setdefault() Returns the value of the >>>car = { "brand": "Ford", “model":
item with the specified "Mustang", "year": 1964 }
key. >>>x = [Link]("color", "white“)
If the key does not exist, insert >>>print(x)
the key, with the specified OUTPUT: White
value.
11
6 sorted() This function is used to sort the >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 ,
key or value of dictionary in 2: 222}
either ascending or descending >>> print(sorted(Dict1))
order. By default, it will sort OUTPUT: {1: 111, 2: 222, 3: 300, 4: 444, 5:
the keys. 555}
To display in descending order. >>>print(sorted(Dict1, reverse = ‘True’))
OUTPUT: {5:555,4:444, 3:333 , 2:222 , 1:111}
7 min() This function returns lowest >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 ,
value in dictionary, this will 2: 222}
work only if all the values in >>>print(min([Link]()))
dictionary is of numeric type. OUTPUT: 111
8 max() This function returns highest >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2:
value in dictionary, this will 222}
work only if all the values in >>>print(max([Link]()))
dictionary is of numeric type. OUTPUT: 555
9 copy() It will create a copy of >>> dict1 = {'Mohan':95, 'Ram':89,
dictionary. 'Suhel':92, 'Sangeeta':85}
>>> dic2 = [Link]()
10 pop() It will remove and returns the >>> dict1 = {'Mohan':95, 'Ram':89,
dictionary element associated 'Suhel':92, 'Sangeeta':85}
to passed key >>> [Link](‘Ram’)
OUTPUT: 89
>>>dict1
OUTPUT: {'Mohan':95,'Suhel':92, 'Sangeeta':85}
11 popitem() It will remove the last >>> dict1 = {'Mohan':95, 'Ram':89,
dictionary item and return 'Sangeeta':85}
key,value. of the removed item >>> k,v = [Link]()
>>> print(k,”: “ v)
OUTPUT: Sangeeta :85
12 get( ) Returns value of a key. >>> [Link]("physics")
Syntax: OUTPUT: 75
[Link](key)
Note: When key does not exist it returns no value without any error.
>>> [Link]('Hindi')
>>>
13 items( ) Returns all elements as a >>> [Link]()
sequence of (key,value) tuples
in any order. OUTPUT: dict_items([('physics', 75),
Syntax: ('Chemistry',78), ('Maths', 81), ('CS', 78)])
[Link]( )
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=[Link]() OUTPUT:
>>> for i, j in seq: 75 physics
print(j, i) 78 Chemistry
81 Maths
78 CS
12
15 values( ) Returns all values in theform >>> [Link]()
of a list. OUTPUT: dict_values([75, 78, 81, 78])
Syntax:
[Link]( )
16 update( ) Merges two dictionaries. >>> d1 = {"physics" : 75, "Chemistry" : 78}
Already present elements are >>> d2 = {"Maths" : 81, "CS":78}
override. >>> [Link](d2)
Syntax: >>> d1
[Link](dictionary2) {'physics': 75, 'Chemistry': 78, 'Maths': 81,
'CS': 78}
1. Program to create a dictionary which stores names of the employee and their salary. (Th/Pr)
num = int(input("Enter the number of employees whose data to be stored: "))
employee = dict() #create an empty dictionary
for i in range(num): OUTPUT:
name = input("Enter the name of the Employee: ") Enter the number of employees whose data
salary = int(input("Enter the salary: ")) to be stored: 2
employee[name] = salary Enter the name of the Employee: abc
print("\n\nEMPLOYEE_NAME\tSALARY Enter the salary: 1200
for k in employee: Enter the name of the Employee: def
print(k,'\t\t',employee[k]) Enter the salary: 2550
EMPLOYEE_NAME SALARY
abc 1200
def 2550
2. Write a program to count the number of characters in a string using dictionary. (Th)
str1 = input("Enter a string: ")
d1 = {} #creates an empty dictionary
for ch in str1:
if ch in d1: #if next character is already in the dictionary
d1[ch] += 1
else: OUTPUT:
d1[ch] = 1 #if ch appears for the first time Enter a string: Hello
for key in d1: Count of characters are: {'H': 1, 'e': 1,
d1=dict(d1) 'l': 2, 'o': 1}
print("Count of characters are:", d1)
13
3. Write a program to create a dictionary with roll no, name and marks of n students in a class and display
the names of students who scored more than 75 marks. (Th/Pr)
OUTPUT:
Enter the number of students:2
Enter Details of Student No: 1
Roll No:01
Student Name:ABC
Marks:85
{1: ['ABC', 85]}
Enter Details of Student No: 2
Roll No:02
Student Name:DEF
Marks:70
{1: ['ABC', 85], 2: ['DEF', 70]}
Student's details who received above 75 marks is/are: ABC
14
#name
print("\nThe email ids in the tuple are:")
print(emails)
print("\nThe username in the email ids are:")
print(username) #Printing the list with the usernames only
print("\nThe domain name in the email ids are:") #Printing the list with the domain names only
print(domainname)
OUTPUT:
How many email ids you want to enter?: 3
> abcde@[Link]
> test1@[Link]
> testing@[Link]
The email ids in the tuple are:
('abcde@[Link]', 'test1@[Link]', 'testing@[Link]')
The username in the email ids are:
('abcde', 'test1', 'testing')
The domain name in the email ids are:
('[Link]', '[Link]', '[Link]')
Question 2:
Write a program to input names of n students and store them in a tuple. Also, input 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
ANSWER:
a) Program:
#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a user-defined function OUTPUT:
#Creating user defined function How many names do you want to enter?: 3
def searchStudent(tuple1,search): > Amit
for a in tuple1: > Sarthak
if(a == search): > Rajesh
print("The name",search,"is present in the tuple") ZThe names entered in the tuple are:
return ('Amit', 'Sarthak', 'Rajesh')
print("The name",search,"is not found in the tuple") Enter the name of the student you want to search? Amit
name = tuple() #Create empty tuple 'name' to store the values The name Amit is present in the tuple
n = int(input("How many names do you want to enter?: "))
for i in range(0,n):
num = input("> ") #It will assign emailid entered by user to tuple 'name'
name = name + (num,)
print("\nThe names entered in the tuple are:")
print(name) #Asking the user to enter the name of the student to search
search = input("\nEnter the name of the student you want to search? ") #Calling the search Student function
searchStudent(name,search)
15
b) Program:
#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a built-in function
name = tuple() #Create empty tuple 'name' to store the values
n = int(input("How many names do you want to enter?: "))
for i in range(0, n):
num = input("> ")
#it will assign emailid entered by user to tuple 'name'
name = name + (num,)
print("\nThe names entered in the tuple are:")
print(name)
search=input("\nEnter the name of the student you want to search? ")
#Using membership function to check if name is present or not
if search in name:
OUTPUT:
print("The name",search,"is present in the tuple")
How many names do you want to enter?: 3
else:
> Amit
print("The name",search,"is not found in the tuple")
> Sarthak
> Rajesh
The names entered in the tuple are:
('Amit', 'Sarthak', 'Rajesh')
Enter the name of the student you want to search?
Animesh
Question 3: The name Animesh is not present in the tuple
Write a Python program to find the highest 2 values in a dictionary.
ANSWER:
Program:
#Write a Python program to find the highest 2 values in a dictionary
#Defining a dictionary
dic = {"A":12,"B":13,"C":9,"D":89,"E":34,"F":17,"G":65,"H":36,"I":25,"J":11}
lst = list() #Creating an empty list to store all the values of the dictionary OUTPUT:
for a in [Link](): #Looping through each values and storing it in list Highest value: 89
[Link](a) Second highest value: 65
#Sorting the list in ascending order, it will store the highest value at the last index
[Link]()
#Printing the highest and second highest value using negative indexing of the list
print("Highest value:",lst[-1])
print("Second highest value:",lst[-2])
Question 4:
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}
16
ANSWER:
Program: OUTPUT:
#Count the number of times a character appears in a given string Enter a string: meritnation
st = input("Enter a string: ") {'m': 1, 'e': 1, 'r': 1, 'i': 2, 't': 2, 'n': 2, 'a': 1, 'o': 1}
dic = {}
#creates an empty dictionary
for ch in st:
if ch in dic:
#if next character is already in the dictionary
dic[ch] += 1
else:
#if ch appears for the first time
dic[ch] = 1
#Printing the count of characters in the string
print(dic)
Question 5:
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
ANSWER:
Program:
dic = {}
#Creates an empty dictionary
#While loop to provide the options repeatedly
#it will exit when the user enters 7
while True:
print("1. Add New Contact")
print("2. Modify Phone Number of Contact")
print("3. Delete a Friend's contact")
print("4. Display all entries")
print("5. Check if a friend is present or not")
print("6. Display in sorted order of names")
print("7. Exit")
inp = int(input("Enter your choice(1-7): "))
#Adding a contact
if(inp == 1):
name = input("Enter your friend’s name: ")
phonenumber = input("Enter your friend's contact number: ")
dic[name] = phonenumber
print("Contact Added \n\n")
17
#Modifying a contact if the entered name is present in the dictionary
elif(inp == 2):
name = input("Enter the name of friend whose number is to be modified: ")
if(name in dic):
phonenumber = input("Enter the new contact number: ")
dic[name] = phonenumber
print("Contact Modified\n\n")
else:
print("This friend's name is not present in the contact list")
#Deleting a contact if the entered name is present in the dictionary
elif(inp == 3):
name = input("Enter the name of friend whose contact is to be deleted: ")
if(name in dic):
del dic[name]
print("Contact Deleted\n\n")
else:
print("This friend's name is not present in the contact list")
#Displaying all entries in the dictionary
elif(inp == 4):
print("All entries in the contact")
for a in dic:
print(a,"\t\t",dic[a])
print("\n\n\n")
#Searching a friend name in the dictionary
elif(inp == 5):
name = input("Enter the name of friend’s to search: ")
if(name in dic):
print("The friend",name,"is present in the list\n\n")
else:
print("The friend",name,"is not present in the list\n\n")
#Displaying the dictionary in the sorted order of the names
elif(inp == 6):
print("Name\t\t\tContact Number")
for i in sorted([Link]()):
print(i,"\t\t\t",dic[i])
print("\n\n")
#Exit the while loop if user enters 7
elif(inp == 7):
break
#Displaying the invalid choice when any other values are entered
else:
print("Invalid Choice. Please try again\n")
OUTPUT:
1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
18
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohit
Enter your friend's contact number: 98765*****
Contact Added
19