0% found this document useful (0 votes)
17 views19 pages

Chapter 10 Tuple & Dictionary Notes.

Uploaded by

nazeema.mca06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views19 pages

Chapter 10 Tuple & Dictionary Notes.

Uploaded by

nazeema.mca06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER- 10 TUPLE & DICTIONARY

➢ 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'

3. min( ) Returns the smallest >>>subject=("Hindi","English","Maths",


value from a tuple. "Physics")
Syntax: >>> min(subject)
min(tuple-name) OUTPUT: 'English'

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'

4 index( ) Returns the index of the first >>>subject=("Hindi","English","Maths",


element with the specified "Physics")
value. >>> [Link]("Maths")
Syntax:
OUTPUT: 2
tuple- [Link](element)
5 count( ) Return the number of >>> [Link]("English")
times the value appears. OUTPUT: 1
Syntax:
tuple- [Link](element)
6 sorted() Takes elements in the tyoke >>>subject=("Hindi","English","Maths",
and returns a new sorted list. "Physics")
It should be noted that, >>> sorted(subject)
sorted() does not make any OUTPUT: [' Hindi', 'English', 'Maths', 'Physics']
change to the original tuple.
7 sum() Returns sum of the elements >>>marks= (19,20,56,18)
of the tuple. >>> sum(marks)
OUTPUT: 113
10.1 Tuple Packing and Unpacking:
Tuple Packing: Creating a tuple from set of values.
Example:
>>> T=(45,78,22)
>>> T
OUTPUT: (45, 78, 22)
Tuple Unpacking : Creating individual values from the elements of tuple.
Example:
>>> a, b, c=T
>>> a
OUTPUT: 45
5
>>> b
OUTPUT: 78
>>> c
OUTPUT: 22
>>> (p, q, r, s) = (5, 6, 8)
OUTPUT: ValueError: not enough values to unpack.
Note: Tuple unpacking requires that the number of variables on the left side must be equalto the length
of the tuple.
10.2 Delete a tuple:
The del statement is used to delete elements and objects but as you know that tuples areimmutable,
which also means that individual element of a tuple cannot be deleted.
Example:
>> T=(2,4,6,8,10,12,14)
>>> del T[3]
OUTPUT: TypeError: 'tuple' object doesn't support item deletion

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}

C. dict( ) constructor using keys and values separately:


>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
OUTPUT: {'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
In this case the keys and values are enclosed separately in parentheses and are given as argument to the
zip( ) function. zip( ) function clubs first key with first value and so on.
D. dict( ) constructor using key-value pairs separately:
Example: -a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> 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'

>>> [Link]( ) #To access all keys in one go


OUTPUT: dict_keys(['physics', 'Chemistry', 'Maths', 'CS'])
>>> [Link]( ) # To access all values in one go
OUTPUT: dict_values([75, 78, 81, 78])
TRAVERSING A DICTIONARY:
Syntax:
for <variable-name> in <dictionary-name>:
statement
Examples:
>>> for i in marks:
print(i, ": ", marks[i])
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
CHANGE AND ADD THE VALUE IN A DICTIONARY:
Syntax:
dictionary-name[key]=value
Examples:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> marks['CS']=84 #Changing a value
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks['English']=89 # Adding a value
8
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
DELETE ELEMENTS FROM A DICTIONARY:
There are three methods to delete elements from a dictionary:
(i) using del statement
(ii) using pop( ) method
(iii) using popitem() method
(iv) using clear() method
Using del statement:
It is used to delete a dictionary item or a dictionary entry, i.e., key:value pair.
If key does not exist it raises exception (KeyError)
If the key is not specified along with the dictionary name with del statement, then it will delete the whole
dictionary.
Syntax:
del dictionary-name[key]
Examples 1:
>>> marks={'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> del marks['English']
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
Examples 2:
>>> del marks['SS']
OUTPUT: KeyError: 'SS'
Examples 3:
>>> del marks
>>> marks
OUTPUT: NameError: name 'marks' is not defined.

Using pop( ) method:


It deletes the key-value pair and returns the value of deleted element. Refer Examples 1
pop() method allows you to specify what to display when the give key does not exist, rather
than the default error message. Refer Examples 2
If the key is not found and the value argument is not pass, Python raises KeyError. Refer
Examples 3
Syntax:
[Link]( key , value)
Examples 1:
>>> marks={'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> [Link]('Maths')
OUTPUT: 81
Examples 2:
>>> [Link]('Eng', 'Not in the dictionary')
OUTPUT: ‘Not in the dictionary
Examples 3:
>>> [Link]('Eng')
OUTPUT: KeyError: 'Eng'
9
Using popitem( ) method:
It will remove the last dictionary item and return key,value pair of the removed item.
The items in the will be removed in the LIFO (Last In First Out) order.
It returns the deleted key:value pair in the form of a tuple i.e., as (key, value).
If the dictionary is empty, calling pop item raises and KeyError.
Syntax:
[Link]( )
Examples 1:
>>> marks= {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> [Link]()
OUTPUT: ('CS', 84)

Using clear( ) method:


It will remove all the items of the dictionary item dictionary becomes empty.
Syntax:
[Link]( )
Examples 1:
>>> marks= {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks
OUTPUT: {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> [Link]()
>>> marks
OUTPUT: {}
DIFFERENCES:
del pop() popitem() clear()
It removes the It deletes an item with It removes only the It removes all the
complete dictionary as a chosen key last entered item from items of the dictionary
an object if the key is the dictionary and makes it empty
not specified. dictionary.
After del statement You can specify the It will raise error if
with a dictionary value or message if dictionary is empty
name, that dictionary the key is not found.
object no longer exists,
not even empty
dictionary

CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:


To check the existence of a key in dictionary, two operators are used:
(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise False.
Examples:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 'Chemistry' in marks
OUTPUT: True
>>> 'CS' not in marks
OUTPUT: False

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

14 keys( ) Returns all keys in theform of >>> [Link]()


a list.
Syntax: OUTPUT: dict_keys(['physics', 'Chemistry',
[Link]( ) 'Maths', '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}

Difference between setdefault() and update():


setdefault() update()
Insert a new key:value pair ONLY if key doesn’t already It merges key:value pairs from the new dictionary into the
exist. original dictionary, adding or replacing as needed.
If key already exist, it returns the current value of the key. The item in the new dictionary is added to the old one and
override any item already there with the same key.

List of Programs prescribed by CBSE:


1. Program to create a dictionary which stores names of the employee and their salary.
2. Write a program to count the number of characters in a string using dictionary.
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.

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)

num=int(input("Enter the number of students:"))


result={}
for i in range(num+1):
print("Enter Details of Student No:", i+1)
roll_no=int(input("Roll No:"))
stud_name=input("Student Name:")
marks=int(input("Marks:"))
result[roll_no]=[stud_name, marks]
print(result)
for k in result:
if result[k][1]>75:
print("Student's details who received above 75 marks is/are:",(result[k][0]))

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

TEXTBOOK EXERCISE PROGRAMS: PG-NO: 224


Question 1:
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()]
ANSWER:
Program:
#Program to read email id of n number of students. Store these numbers 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.
emails = tuple()
username = tuple()
domainname = tuple()
#Create empty tuple 'emails', 'username' and domain-name
n = int(input("How many email ids you want to enter?: "))
for i in range(0,n):
emid = input("> ")
emails = emails +(emid,) #It will assign emailid entered by user to tuple 'emails'
spl = [Link]("@") #This will split the email id into two parts, username and domain and return a list
username = username + (spl[0],) #assigning returned list first part to username and second part to domain name
domainname = domainname + (spl[1],) #assigning returned list first part to username and second part to domain

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

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
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohan
Enter your friend's contact number: 98764*****
Contact Added

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
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 7

19

You might also like