CH.
2 PYTHON REVISION TOUR II
String Operators:
String Concatenation Operator + : The + operator creates a new
string by joining two or more string operand. All the operands must
be same data type.
String Replication Operator * : This operator is used to replicate
the string.
Membership Operators: There are two membership operators.
in Operators: It returns True if a substring exists in the given string
otherwise it returns False. Strings are case sensitive.
not in Operators: It returns True if a substring does not exist in the
given string otherwise it returns False.
Comparison Operators: It returns True if a substring does not exist
in the given string otherwise it returns False.
FName = "Anil"
password = "Computer"
MName = "Krishna" Pass=input("Enter your password: ")
SName = "Yadav" if Pass == password:
print(FName + MName + SName) print("Correct Password.")
print(FName * 3) else:
if "A" in FName: print("Wrong Password.")
print("A is in", FName)
else:
print("A is not in", FName)
AnilKrishnaYadav
AnilAnilAnil
A is in Anil
ord( ) function: It is a built-in function that takes a single character
and returns the corresponding ASCII value or Unicode value.
chr( ) function: It is a built-in function that takes a ASCII value in
integer form and returns the character corresponding to that ASCII
value.
>>> ord("A")
65
>>> chr(66)
'B‘
len( ) function: This function is used to find the total number of
characters in a string.
>>> name = “deepak"
>>> len(name)
6
capitalize( ) function: Returns a copy of the string with its first
character capitalized.
>>> name="deepak"
>>> name.capitalize()
'Deepak'
find(sub,start,end) function: Returns the lowest index in the string
where the substring sub is found within the slice range of start and
end. Returns -1 if sub is not found.
>>> chap = "Python Revision Tour 2"
>>> chap.find("Tour",5,10)
-1
>>> chap.find("Tour",10,20)
16
isalnum( ) function: Returns True if the characters in the string are
alphabets or numbers or alphanumeric; False otherwise.
>>> cid = "MCA001"
>>> cid.isalnum()
True
>>> courseid="BCA 001"
>>> courseid.isalnum()
False
isalpha( ) function: Returns True if all the characters in the string
are alphabetic; False otherwise.
>>> post = "Manager"
>>> post.isalpha()
True
>>> PId = "P001"
>>> PId.isalpha()
False
isdigit( ) function: Returns True if all the characters in the string are
digits; False otherwise.
>>> PId = "P001"
>>> PId.isdigit()
False
>>> CId = "001"
>>> CId.isdigit()
True
isspace( ) function: Returns True if all the characters in the string
are whitespace; False otherwise.
>>> str = " "
>>> str.isspace()
True
>>> str2 = "Python Program"
>>> str1 = ""
>>> str2.isspace()
>>> str1.isspace()
False
False
islower( ) function: Returns True if all the characters in the string
are in lower case; False otherwise.
>>> FName = "Deepak"
>>> FName.islower()
False
>>> SName = "singh"
>>> SName.islower()
True
isupper( ) function: Returns True if all the characters in the string
are in upper case; False otherwise.
>>> FName = "Deepak"
>>> FName.isupper()
False
>>> SName = “SINGH"
>>> SName.isupper()
True
lower( ) function: Returns a copy of the string converted to
lowercase.
>>> FName = "DEEPAK"
>>> FName.lower()
“deepak”
>>> FName
“DEEPAK”
upper( ) function: Returns a copy of the string converted to
uppercase.
>>> SName = “singh"
>>> SName.upper()
“SINGH”
>>> SName
“singh”
lstrip( ) function:
Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading
whitespaces.
All the possible combinations of the argument are stripped.
Argument is case sensitive.
>>> name=“ Deepak Singh” #Note a space before Deepak
>>> name.lstrip()
'Deepak Singh’ #Space is removed before Deepak in the copy
>>> name
‘ Deepak Singh’ #But space remains in the original string
>>> s = "History"
>>> s.lstrip("Hi")
'story'
>>> s.lstrip("iH")
'story'
rstrip( ) function:
Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the trailing
whitespaces.
All the possible combinations of the argument are stripped.
Argument is case sensitive.
>>> s=“History “ # Note a space after History
>>> s.rstrip()
‘History’ # Space is removed in the copy
>>> s
“History “ # Space remains in the original string
>>> s = “History”
>>> s.rstrip("tory")
'His'
>>> s.rstrip("rtyo")
'His'
What is a list in Python?
Ans. A list in Python is a compound data type because it can store
any data type in it.
ListVariable = [List of Values]
L1 = [10,25,3,99,105]
L2 = *“Ram”, “Raheem”, “Deepa”, “Ashok”+
L3 = *1, “Ram”, 2, “Raheem”, 3, “Deepa”+
L4 = *1, “Ram”, 85.25, 2, “Raheem”, 75.5+
L5 = *25, 36, 60.251, 33, 0.25, “Python”+
What is an empty list?
Ans. A list without any element is called empty list.
L=[] # L is an empty list.
An empty list can also be created as follows:
L = list( ) # L is an empty list.
What is a nested list?
Ans. A list within a list is called as nested list.
>>> L = [1, 2, 3, [10, 20, 30], 4, 5]
>>> L
[1, 2, 3, [10, 20, 30], 4, 5]
>>> L[0]
1
>>> L[0:3] >>> L[3][0]
[1, 2, 3] 10
>>> L[0:5] >>> L[3][0:3]
[1, 2, 3, [10, 20, 30], 4] [10, 20, 30]
>>> L[7]
IndexError: list index out of range
Creating a list with keyboard using list( ) function:
L = list(input("Enter List Element: "))
print("The List is: ",L)
Enter List Element: PYTHON
The List is: ['P', 'Y', 'T', 'H', 'O', 'N']
Enter List Element: 15,75
The List is: ['1', '5', ',', '7', '5']
The list( ) function always creates a string type of list even though if
we enter digits. To enter a list of integers, float, string or compound
data types the following method is used:
L = eval(input("Enter list: "))
print("The list is: ",L)
Enter list: [25,5.5,"Python",100]
The list is: [25, 5.5, 'Python', 100]
The eval( ) Function: This function can be used to evaluate and
return the result of an expression given as a string. E.g.
Result=eval('5*7')
print(Result) # Output will be 35
>>> Expression = eval(input("Enter an Expression: "))
Enter an Expression: 3+5*5-2
>>> print(Expression)
26
Difference between Lists and Strings:
Storage: List are stored in memory exactly like strings, except that because
some of their objects are larger than others, they store a reference at each
index instead of single characters as in strings.
Mutability: String are not mutable while the lists are. E.g.
L[0] = 50 will replace the element 5 with new value 50 at index zero(0).
S*0+ = “p” will generate a Type Error: 'str' object does not support item
assignment
Similarity between Lists and Strings:
List String
L = *5, 25.5, 10+, L1=*“Dev”,1+ S = “Python”, S1 = “Program”
len(L) will return 3 i.e. number of len(S) will return 6 i.e. number of
elements. characters.
L[i] will return the element at index i. S[i] will return the character at index i.
L[i:j] will return the element from i S[i:j] will return the characters from i
to j-1. to j-1.
30 in L will return False. “A” in S will return False.
30 not in L will return True. “A” not in S will return True.
5 in L will return True. “P” in S will return True.
5 not in L will return False. “P” not in S will return False
L + L1 will return *5,25.5,10,”Dev”,1+ S+S1 will return “PythonProgram”
L*2 will return [5,25.5,10, 5,25.5,10] S*2 will return PythonPython
Making True copy of a List: L1 10 20 30 Elements
L1 = [10,20,30] 0 1 2 Index
L2 = L1 L2
Assigning a list to another list does not make a copy instead assignment (=)
operator makes two variables point to the one list in the memory. This is
called as Shadow copy.
So if you make changes in one list, the other list will also report these
changes because these two list names are labels referring to same list.
To make a true copy of any list i.e. independent copy you should use list()
function as follows:
L2 = list(L1)
10 20 30 Elements
L1
0 1 2 Index
10 20 30 Elements
L2
0 1 2 Index
Accessing List:
List = eval(input("Enter List Elements: "))
length=len(List)
for L in range(length):
print("At indexes ",L," and ",(L-length),
"Element is: ",List[L])
Enter List Elements: [2.5,10,25,30,45.25,125]
At indexes 0 and -6 Element is: 2.5
At indexes 1 and -5 Element is: 10
At indexes 2 and -4 Element is: 25
At indexes 3 and -3 Element is: 30
At indexes 4 and -2 Element is: 45.25
At indexes 5 and -1 Element is: 125
Comparing List: >>> L1==L5
True
>>> L1=[1,2,3] >>> L1==L3
>>> L2=[4,5] False
>>> L3=[6,7,8] >>> L1==L2
>>> L4=[9,10,11,12] False
>>> L5=[1,2,3] >>> L1<L2
>>> L6=[25,30] True
>>> L7=[6,7,100] >>> L1<L3
True
>>> L4<L6
True
>>> L3<L7
True
>>> L2>L1
True
Joining Lists: Two or more lists can be joined using concatenation
(+) operator. A List can only be concatenated with other list; no
other data types can be concatenated.
>>> L1=[1,2,3] >>> L+[100]
>>> L2=[4,5] [1, 2, 3, 100]
>>> L3=*‘PHY’, ‘CHEM’, ‘BIO’+ >>> L
>>> L4=L1+L2+L3 [1, 2, 3]
>>> L4
[1, 2, 3, 4, 5, ‘PHY’, ‘CHEM’, ‘BIO’]
>>> L1+75
TypeError: can only concatenate list (not "int") to list
>>> L1+"Python“
TypeError: can only concatenate list (not "str") to list
Replicating Lists: Like strings we can replicate list using
Replication (*) operator to a specified number of times.
>>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Slicing the Lists: We can create another list from existing list or
we can create list slices as follows: >>> L=L1[0:6:2]
ListSlice = List[start : stop] >>> L
ListSlice = List[start : stop : step] [10, 30, 50]
>>> L1=[10, 20, 30, 40, 50, 60] L=L1[0: :2]
>>> L=L1[0 : 3] >>> L
>>> L [10, 30, 50]
[10, 20, 30] >>> L=L1[: : -1]
>>> L
[60, 50, 40, 30, 20, 10
>>> L1 = ['ENG','PHY','CHEM','MATH','CS']
>>> L2 = [10, 20, 30, 40, 50, 60]
>>> L = L1 + L2
>>> L
['ENG', 'PHY', 'CHEM', 'MATH', 'CS', 10, 20, 30, 40, 50, 60]
>>> L2[0:3]=[15,25,35]
>>> L2
[15, 25, 35, 40, 50, 60]
>>> L2*0:3+=“A”
>>> L2
*‘A’, 40, 50, 60+
>>> L=[1,2,3]
>>> L[0:2]="456"
>>> L
['4', '5', '6', 3]
>>> L[0:1]="789"
>>> L
['7', '8', '9', '5', '6', 3]
>>> L[0:2]="A"
>>> L
['A', '9', '5', '6', 3]
>>> L[10:15]="21"
>>> L
['A', '9', '5', '6', 3, '2', '1']
del Statement: This statement can be used to remove an
individual item, or to remove all items identified by a slice or to
delete the list from the computer memory.
del List[index]
del List[start : stop] >>> L=[10,20,30]
del List >>> del L[5]
>>> L=[10,20,30,40,50] IndexError: list assignment index out of range
>>> del L[3] >>> del L[1:3]
>>> L >>> L Note: Element deleted by
[10, 20, 30, 50] [10] del can not be assigned to
>>> del L[1:3] >>> L=[50,60,70,80] any variable because this
>>> L >>> del L[5:10] does not return any value.
[10, 50] >>> L
>>> del L [50, 60, 70, 80]
>>> L
NameError: name 'L' is not defined
index( ) Function: This function returns the index of first
matched element from the list.
ListName.index(element)
>>> L=[10,20,30,40,50,30,60]
>>> L.index(40)
3 Index--- 0 1 2 3 4 5 6
>>> L.index(30) Values--- 10 20 30 40 50 30 60
2
>>> L.index(35)
ValueError: 35 is not in list
append( ) Function: This function adds an element at the end of
the list. This function does not return any value.
Syntax:
ListName.append(element)
>>> L=[10,20,30,40,50]
>>> L.append(60)
>>> L
[10, 20, 30, 40, 50, 60]
>>> L1=L.append(70)
>>> L1 # L1 is empty because append function
>>> L does not return any value but L is
[10, 20, 30, 40, 50, 60, 70] appended.
extend( ) Function: This function is used to add multiple
elements to a list. This function takes a list as an argument and
appends all of the elements of the argument list to the list object
on which extend( ) is applied.
Syntax:
ListName.extend (List)
>>> L1=[10,20,30]
>>> L2=[40,50,60]
>>> L1.extend(L2)
>>> L1
[10, 20, 30, 40, 50, 60]
>>> L3=[70,80,90]
>>> L=L1.extend(L3) # L is empty because extend function
>>> L does not return any value but L1 is
>>> L1 extended.
[10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> L2.extend([70,80])
>>> L2
[40, 50, 60, 70, 80]
insert( ) Function: This function is used to insert an element in
the list at desired index. This function takes two arguments and
returns no value.
Syntax:
ListName.insert (index, element)
Index--- 0 1 2 3 4 0 1 2 3 4 5
Values--- 10 20 30 40 50 10 60 20 30 40 50
>>> L=[10, 20, 30, 40, 50] >>> L.insert(10,80)
>>> L.insert(1,60) >>> L
>>> L [10, 60, 20, 30, 40, 50, 70, 80]
[10, 60, 20, 30, 40, 50] >>> L.insert(-10,90)
>>> L.insert(len(L),70) >>> L
>>> L [90, 10, 60, 20, 30, 40, 50, 70, 80]
[10, 60, 20, 30, 40, 50, 70]
pop( ) Function:
This function is used to remove an element from the list at
desired index.
This function takes index as an arguments and returns the value
which is being deleted.
If no index is passed in the argument then this function
removes the last element from the list.
Syntax: Index--- 0 1 2
ListName.pop (index) >>> L.pop() Values--- 10 20 30
>>> L = [10, 20, 30] 30
>>> L 0 1
>>> L.pop(1)
[10] 10 30
20
>>> L >>> A = L.pop()
0
[10, 30] >>> A
10 10
remove( ) Function:
This function is used to remove the first occurrence of given
element from the list.
This function takes a value as an arguments and does not return
anything.
Syntax:
ListName.remove (element)
>>> L.remove(55)
>>> L=[10,20,30,10,40,10,50] ValueError: list.remove(x): x not
>>> L.remove(10) in list
>>> L L.remove()
[20, 30, 10, 40, 10, 50] TypeError: remove() takes
>>> L.remove(10) exactly one argument (0 given)
>>> L
[20, 30, 40, 10, 50]
clear( ) Function:
This function is used to remove all the elements from the list.
This function does not return anything.
Syntax:
ListName.clear () >>> max(L)
50
>>> L=[20, 30, 40, 10, 50] >>> min(L)
>>> L.clear() 10
>>> L
[]
count( ) Function:
This function returns the count of the element that you passed
as an argument.
>>> L=[10,15,10,20,30,10]
Syntax:
>>> L.count(10)
ListName.count (element)
3
reverse( ) Function:
This function reverses the elements of the list and stores in the
same list variable. This function does not return anything.
Syntax:
ListName.reverse ()
sort( ) Function:
>>> L=[10,5,30] This function sorts the elements of the
>>> L.reverse() list and stores in the same list variable.
>>> L This function does not return anything.
[ 30,5,10] Syntax:
ListName.count (element)
>>> L=[10,5,25,20]
>>> L.sort()
>>> L
[25,20,10,5]
Creating a List from a Tuple:
>>> Tuple=(10,20,30)
>>> L=list(Tuple)
>>> L
[10, 20, 30]
Creating a List from a Dictionary:
>>> Dict={1:"Kartik",2:"Deepak",3:"Puja"}
>>> L1=list(Dict)
>>> L1
[1, 2, 3]
Note: The keys of the dictionary are the elements of the list.
Creating a Tuple:
T = () # It will create an empty tuple
T = tuple() # It will also create an empty tuple
Creating a tuple from Existing Sequences (List, String, Dictionary):
T = tuple(sequences)
>>> L=[1,2,3]
>>> S="PYTHON"
>>> D={10:"A",20:"B"} >>> T3
>>> T1=tuple(L) (10, 20)
>>> T2=tuple(S) >>> T4=tuple(T2)
>>> T3=tuple(D) >>> T4
>>> T1 ('P', 'Y', 'T', 'H', 'O', 'N')
(1, 2, 3) >>> T5=(T1+T2)
>>> T2 >>> T5
('P', 'Y', 'T', 'H', 'O', 'N') (1, 2, 3, 'P', 'Y', 'T', 'H', 'O', 'N')
Creating a Tuple from Keyboard using input() Function:
With this method the elements of a tuple will be single character
or single digit.
#Program to create a tuple.
T1 = tuple(input("Enter a String: "))
T2 = tuple(input("Enter a sequence of Digits: "))
print("Tuple of String is: ",T1)
print("Tuple of Digit is: ",T2)
#Output
Enter a String: python
Enter a sequence of Digits: 258
Tuple of String is: ('p', 'y', 't', 'h', 'o', 'n')
Tuple of Digit is: ('2', '5', '8')
Creating a Tuple from Keyboard using eval() Function:
With this method the elements of a tuple may have more than one
characters in a string or more than one digits.
#Program to create a tuple.
T1 = eval(input("Enter the Elements of Tuple: "))
print("Tuple is: ",T1)
#Output
Enter the Elements of Tuple: "Class",12,"Python"
Tuple is: ('Class', 12, 'Python')
Note: Tuples are immutable but it can be indirectly modified.
Indirect Modification of Tuples using Tuple Unpacking:
>>> T=(1,2,3)
Step 1: First unpack the tuple.
>>> a,b,c=T # Unpacking
Step 2: Change the value.
>>> a=10
Step 3: Repack the tuple with changed value
>>> T=(a,b,c)
>>> T
(10, 2, 3)
Indirect Modification of Tuples using constructor functions i.e.
list( ) and tuple( ):
>>> T=(10,20,30)
Step 1: Convert the tuple to list using list ( ) function:
>>> L=list(T)
>>> L
[10, 20, 30]
Step 2: Make changes in the desired element in the list
>>> L[0]=100
>>> L
[100, 20, 30]
Stpe 3: Create a tuple from the modified list with tuple( ) function
>>> T=tuple(L)
>>> T
(100, 20, 30)
Indexing and Slicing
Membership Operators
Concatenation and Replication Operators
Accessing Individual Elements
Joining Tuples
len()
max()
min()
index()
count()
The above operations are done same way as it is done for list.
Note: Tuple is immutable hence once the tuple is created the
element of it cannot be modified or deleted.
Dictionaries in Python:
Dictionaries are mutable, unordered collections of elements in the form of a
key : value pairs.
It is used to process huge amount of data in an efficient way.
Each value is assigned to an unique key which is non-mutable type.
Instead of using index number each value is accessed using key.
Syntax:
DictionaryName = {Key : Value, Key : Value, ………..-
Name_Add = {“Jaya” : “Nerul”, “Suraj” : “Vashi”-
Adding Elements to Dictionary:
DictionaryName[key] = value
Name_Add*“Deepak”+ = “Nerul”
Name_Add = {“Jaya” : “Nerul”, “Suraj” : “Vashi”, “Deepak” : “Nerul”-
Ways of Creating Dictionaries:
D1 = { } # Empty Dictionary
D2 = dict( ) # Empty Dictionary
D3 = {1:"A",2:"B",3:"C"}
D4 = dict(Name="Krishna", Age=21, Address="Belapur")
D5 = dict({"Name" : "Krishna", "Age" : 21})
D6 = dict(zip(("Name","Roll Number","Division"),("Puja",15,"A")))
D7 = dict((("Name","Krishna"),("Roll Number",10)))
D8 = dict([["Name", "Puja"], ["Class", "XII"], ["Marks", 85]])
D9 = dict((["Name", "Puja"], ["Class", "XII"], ["Marks", 85]))
Accessing Elements of a Dictionary:
student = {"Name": "Krishna", "Age": 21, "Address": "Belapur"}
print("Printing values using key:")
print(student["Name"])
print(student["Age"])
print(student["Address"])
print("Printing all keys one by one using for loop:")
for k in student:
print(k)
print("Printing all values one by one using for loop:")
for k in student:
print(k,":", student[k])
The keys() Function: It is used with dictionaries to retrieve all the keys as a
view object. It doesn't return a list directly.
>>> D = {"Name" : "Krishna", "Age" : 21, "Address" : "Belapur"}
>>> D.keys()
dict_keys(['Name', 'Age', 'Address'])
The values() Function: It is used with dictionaries to retrieve all the values as a
view object. It doesn't return a list directly.
>>> D = {"Name" : "Krishna", "Age" : 21, "Address" : "Belapur"}
>>> D.values()
dict_values(*‘Krishna’, 21, ‘Belapur’+)
items() function: This function is used with dictionaries to return a view
object that displays all the key-value pairs as tuples in a list. As the items()
function returns a sequence of pairs, we can write a loop having two variables
to access key value pairs.
Syntax:
DictionaryName.items()
D = {'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
print(D.items())
L=D.items()
for k,v in L:
print(k,":",v)
dict_items([('Name', 'Deepak'), ('Age', 21), ('Address', 'Belapur')])
Name : Deepak
Age : 21
Address : Belapur
get() function: The get() method in Python is used with dictionaries to retrieve
the value associated with a specific key.
Functionality:
It takes a key as the first argument. It optionally takes a default value as the
second argument. If the key exists in the dictionary, get() returns the value
associated with that key.
If the key doesn't exist:
• If a default value is provided (second argument), get() returns the default
value.
• If no default value is provided, get() returns None.
Syntax:
DictionaryName.get(Key, Message)
>>> D = {'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
>>> D.get('Name','Key does not exist.')
'Deepak'
>>> D.get('SName','Key does not exist.')
'Key does not exist.'
update() function:
Parameters(optional): An iterable object of key-value pairs (dictionary) is
used to update the dictionary. If not provided, the dictionary remains
unchanged.
Return value: The update() method doesn't return any value. It directly
modifies the dictionary it's called on.
Behavior: If the key exists in the dictionary the value in the dictionary
gets updated with the new value. If a key doesn't exist in the dictionary,
it gets added with the corresponding new value.
d = {1: "Aman", 2: "Deep"}
d.update({1: "Jai"})
print(d)
Output: {1: 'Jai', 2: 'Deep'}
d = {1: "Aman", 2: "Deep"}
d.update()
print(d)
Output: {1: "Aman", 2: "Deep"}
d = {1: "Aman", 2: "Deep"}
d.update({3: "Krish"})
print(d)
Output: {1: 'Aman', 2: 'Deep', 3: 'Krish'}
d = {1: "Aman", 2: "Deep"}
marks = {"Aman": 15, 2: "Priya"}
d.update(marks)
print(d)
Output: {1: 'Aman', 2: 'Priya', 'Aman': 15}
clear() function:
This function is used with dictionaries to remove all key-value pairs from
the dictionary. It effectively empties the dictionary. It modifies the
original dictionary. It does not return any value.
d = {'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
d.clear()
print(d) # Output will be: { }
fromkeys() function:
This function in Python is used to create a new dictionary from a
sequence of elements (like a list, tuple, or string) as keys, and assigns a
user-specified value to all the keys.
Parameters:
sequence: This is a required argument that can be any iterable object
(like a list, tuple, or string) containing the keys for the new dictionary.
value (optional): This is an optional argument that specifies the value to
be assigned to all the keys in the new dictionary.
If no value is provided, the keys are initialized with a value of None by default.
Returns: A new dictionary with keys from the provided sequence and the
specified value assigned to each key.
Key points about fromkeys():
Creates a new dictionary: It's important to note that fromkeys() doesn't
modify existing dictionaries. It creates a new dictionary with the specified keys
and values.
Default value: If you don't provide a value argument, all the keys in the new
dictionary will be assigned a value of None.
e.g.
indicators = ["Red", "Yellow", "Green"]
signal1 = dict.fromkeys(indicators, "OFF")
signal2 = dict.fromkeys(indicators)
print(signal1) # Output: {'Red': 'OFF', 'Yellow': 'OFF', 'Green': 'OFF'}
print(signal2) # Output: {'Red': None, 'Yellow': None, 'Green': None}
copy() function: It creates a shallow copy, meaning it copies only the
references to the original keys and values in the dictionary. If the values in the
original dictionary are mutable objects (like lists or other dictionaries), those
objects themselves aren't copied. They are still referenced by the new
dictionary.
e.g.
sdetail = {1: "Jai", 2: "Priya", 3: [10, 20]}
sdetail_copy = sdetail.copy()
sdetail_copy[1] = "Ram"
sdetail_copy[3][1] = 50
print(sdetail)
print(sdetail_copy)
Output:
{1: 'Jai', 2: 'Priya', 3: [10, 50]}
{1: 'Ram', 2: 'Priya', 3: [10, 50]}
pop() function: The pop() method in Python is used with dictionaries to remove a
specified element (key-value pair) and return its value.
Parameters:
key: This is the required argument, which specifies the key of the element you
want to remove from the dictionary.
default (optional): This is an optional argument that specifies the value to return
if the key doesn't exist in the dictionary. If no default value is provided, a KeyError
exception is raised.
Return value:
The pop() method returns the value associated with the removed key.
If the key doesn't exist and no default value is provided, it raises a KeyError
exception.
e.g.
student = {"Name": "Krishna", "Age": 21, "Address": "Belapur"}
del_ele = student.pop("Name")
print(del_ele)
del_ele = student.pop("Roll Number") # Raises a KeyError: 'Roll Number'
del_ele = student.pop("Roll Number", "Key does not exist.")
print(del_ele)
popitem() function: The popitem() method in Python is used with dictionaries
to remove and return an arbitrary key-value pair (element) from the
dictionary.
Removes and returns an element: Unlike pop(key), which requires you to
specify the key, popitem() removes last element and returns key-value pair
from the dictionary.
No arguments: The popitem() method doesn't take any arguments.
Return value: popitem() returns a tuple containing the key and value of the
removed element.
e.g.
student = {"Name": "Krishna", "Age": 21, "Address": "Belapur"}
del_ele = student.popitem()
print(del_ele)
setdefault() function: The setdefault() method in Python is used with
dictionaries to retrieve a value for a key and, if the key doesn't exist, it inserts
that key into the dictionary with a specified default value.
Parameters:
key: This is the required argument that specifies the key you want to access
or add.
default (optional): This is an optional argument that specifies the value to
insert into the dictionary if the key doesn't exist. If no default value is
provided, None is used by default.
Return value:
If the key already exists in the dictionary, setdefault() returns the value
associated with that key.
If the key doesn't exist, it inserts the key into the dictionary with the specified
default value and then returns the default value.
e.g.
student = {"Name": "Krishna", "Age": 21, "Address": "Belapur"}
val1 = student.setdefault("GrNo")
print(val1)
print(student)
val2 = student.setdefault("House","No House")
print(val2)
print(student)
Output:
None
{'Name': 'Krishna', 'Age': 21, 'Address': 'Belapur', 'GrNo': None}
No House
{'Name': 'Krishna', 'Age': 21, 'Address': 'Belapur', 'GrNo': None, 'House': 'No House'}
student = {11: "Ram", 2: "Krishna", 35: "Bharat"}
print(max(student))
print(min(student))
a = sorted(student)
print(a)
print(student)
Output:
35
2
[2, 11, 35]
{11: 'Ram', 2: 'Krishna', 35: 'Bharat'}
Creating List and Tuple using Dictionary by list() and tuple()
functions:
>>> D = {"Name" : "Krishna", "Age" : 21, "Address" : "Belapur"}
>>> L=list(D.keys())
>>> L
['Name', 'Age', 'Address']
>>> L1=list(D.values()) # List is created
>>> L1
['Krishna', 21, 'Belapur']
>>> T=tuple(D.keys()) # Tuple is created
>>> T
('Name', 'Age', 'Address')
>>> T1=tuple(D.values()) # Tuple is created
>>> T1
('Krishna', 21, 'Belapur')
Nested Dictionary: Storing a dictionary as a value inside another dictionary
is called nested dictionary.
Student={“Om” : {"Roll Number“ : 10,"Class“ : "XII“, "Marks“ : 55-,
“Saheel” : {"Roll Number“ : 27,"Class“ : "XII", "Marks“ : 45-,
“Siya” : {"Roll Number“ : 3,"Class“ : "XII", "Marks“ : 70-
}
for k in Student: Student's Name: Deep
Roll Number: 10
print("Student's Name: ",k)
Class: XII
print("Roll Number: ",Student[k]["Roll Number"]) Marks: 55
print("Class: ",Student[k]["Class"])
print("Marks: ",Student[k]["Marks"]) Student's Name: Saheel
print() Roll Number: 27
Class: XII
Marks: 45
Student's Name: Siya
Roll Number: 3
Class: XII
Marks: 70
Updating Existing Elements in a Dictionary:
>>> D = {"Name" : "Krishna", "Age" : 21, "Address" : "Belapur"}
Updating the Value of a Key:
>>> D[“Name”+ = “Deepak”
>>> D
{'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
Note: If key does not exist then the new entry will be added in the
dictionary
Renaming the Keys of a Dictionary:
>>> D["SName"] = D["Name"]
>>> D
{'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur', 'SName': 'Deepak'}
>>> del D["Name"]
>>> D
{'Age': 21, 'Address': 'Belapur', 'SName': 'Deepak'}
Renaming the Key of a Dictionary using pop( ) Function:
>>> D = {'Age': 21, 'Address': 'Belapur', 'SName': 'Deepak'}
>>> D["SAge"] = D.pop("Age")
>>> {'Address': 'Belapur', 'SName': 'Deepak', 'SAge': 21}
Deleting Elements from a Dictionary: An elements can be deleted
from a dictionary using following statement.
>>> D = {'Address': 'Belapur', 'SName': 'Deepak', 'SAge': 21}
>>> del D["Address"]
>>> D
{'SName': 'Deepak', 'SAge': 21} # Address key is deleted
Checking for Existence of a Key or Value: The membership operators
in and not in are used to check whether the key exist or not.
>>> D = {'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
>>> "Name" in D
True
>>> "Marks" in D
False
>>> "Percent" not in D
True
NOTE: These membership operators does not work directly on the
values of a dictionary. The values can be checked using values() function.
>>> "Deepak" in D.values()
True
>>> "Belapur" not in D.values()
False
Program to input keys and values through keyboard and store in a
dictionary.
percent = {} # Empty Dictionary
n = int(input("Enter the number of students: "))
for s in range(n):
key = input("Enter the name of student: ")
value = float(input("Enter the percentage scored: "))
percent[key] = value
print(“\nName and Percent in the Dictionary is now: ")
print(percent) Enter the number of students: 2
Enter the name of student: Deep
Enter the percentage scored: 65.5
Enter the name of student: Jaya
Enter the percentage scored: 50
Name and Percent in the Dictionary is now:
,‘Deep': 65.5, ‘Jaya': 50-
Program to count the frequency of a list elements using a
dictionary.
from json import dumps
sentence = "This is Python programming. Python is very easy to learn."
words = sentence.split()
d = {}
for w in words: Counting the frequencies in a list:
key = w {
if key not in d: "This": 1,
count = words.count(key) "is": 2,
"Python": 2,
d[key] = count "programming.": 1,
print("Counting the frequencies in a list:") "very": 1,
print(json.dumps(d,indent=3)) "easy": 1,
"to": 1,
"learn.": 1
}
dumps() Function: This function is used to print the elements of a
dictionary in more readable and presentable format. To use this
function one needs to import json module.
Syntax:
json.dumps(DictionaryName, indent)
import json
D = {'Name': 'Deepak', 'Age': 21, 'Address': 'Belapur'}
print("Printing Dictionary in more readable format.")
print(json.dumps(D,indent=3))
Printing Dictionary in more readable format.
{
"Name": "Deepak",
"Age": 21,
"Address": "Belapur"
}