Ch No 3 Data Structure in Python
Ch No 3 Data Structure in Python
MARKS:14
COURSE OUTCOME
🞆 Perform operation on Data Structure in
Python
List
LIST
🞆 A list is a collection which is ordered and
changeable. In Python lists are written with
square brackets.
🞆 The list is a most versatile data type
available in Python which can be written as a
list of comma-separated values (items)
between square brackets.
🞆 Important thing about a list is that items in a
list need not be of the same type.
CREATING A LIST
🞆 Creating a list is as simple as putting
different comma-separated values between
square brackets. For example −
>>> list6=list("ABCdef123")
>>> list6
['A', 'B', 'C', 'd', 'e', 'f', '1', '2', '3']
ACCESSING VALUES IN LISTS
print("list1:",list1)
print("list1[0]:",list1[0])
print("list1[-2]:",list1[-2])
print("list1[1:3]:",list1[1:3])
print("list1[3:]:",list1[3:])
print("list1[:4]:",list1[:4])
OUTPUT
list1: ['one', 'two', 3, 10, 'six', 20]
list1[0]: one
list1[-2]: six
list1[1:3]: ['two', 3]
list1[3:]: [10, 'six', 20]
list1[:4]: ['one', 'two', 3, 10]
COPYING THE LIST
🞆 We can make a duplicate or copy of an existing list.
For Example.
List1=[10,20,30,40]
List2=List1
In the first statement List1 is pointing to the
List[10,20,30,40]
In The second statement we are not copying List
but we are making another variable List2 and attach
it to the list pointed by List1.
Both Variable are pointing to the same list.
Due to this if we modify the List1 ,then the
modification will also take place and vice versa. in
List2
EXAMPLE
List1=[10,20,30,40]
List2=List1
print(List2)
List1.append(50)
print(List1)
print(List2)
Output:
[10, 20, 30, 40]
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
🞆 There are two ways to make a copy of a List
1.Using [:] operator
For Example:
List1=[10,20,30,40]
List2=List1[:]
print(List1)
print(List2)
Output
[10, 20, 30, 40]
[10, 20, 30, 40]
2.using Built in copy Function
It use copy function to make copy of an existing list.
In order to use copy function,first we have to import
For example
from copy import copy
List1=[10,20,30,40]
List2=copy(List1)
print(List1)
print(List2)
Output
[10, 20, 30, 40]
[10, 20, 30, 40]
LIST ARE MUTABLE
🞆 The value of any element inside the List can
be changed at any point of time.
🞆 The Elements of the List are accessible with
their index value.The index always start with
0 and ends with n-1,if the list contains n
elements.
🞆 Example
List1=[10,20,30,40]
List1[2]=50
print(List1)
Output
[10, 20, 50, 40]
UPDATING LISTS
>>> list1=[10,20,30,40,50]
>>> list1[1:4]=[99,98,97]
>>> list1
[10, 99, 98, 97, 50]
#Modifying a list using slicing
list1=[10,20,30,40,50]
>>> list1[2:2]=[99,98,97]
>>> list1
[10, 20, 99, 98, 97, 30, 40, 50]
list1=[10,20,30,40,50]
>>> list1[3:2]=[99,98,97]
>>> list1
[10, 20, 30, 99, 98, 97, 40, 50]
FOLLOWING METHODS USED FOR
UPDATING LIST
1. append()
Syntax:
list.append(item)
-The item can be numbers,string,another list,dictionary etc.
-only modifies the original list.It does not return any value.
2. extend()
Syntax:
list1.extend(list2)
-This extend() method takes a list and adds it to the end.
-only modifies the original list.It does not return any value.
3. insert()
4. Syntax:
list.insert(index,element)
-The index is position where an element needs to be
inserted.
only modifies the original list.It does not return any value.
1.append()
The append() method adds an element to the
end of a list.We can insert a single item in
the list.
>>> list1=[10,20,30,40]
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,70])
>>> list1
[10, 20, 30, 40, 60, 70]
3. insert()
We can insert one single item at a desired
location by using the method insert() or insert
multiple items by squeezing it into an empty
slice of a list
>>> list1.insert(1,30)
>>> list1
[10, 30, 20]
DELETE LIST ELEMENTS
list1=[10,20,30,40]
>>> list1
[10, 20, 30, 40]
>>> del(list1[1])
>>> list1
[10, 30, 40]
>>> list1.remove("one")
>>> list1
[10, 'two']
BASIC LIST OPERATIONS
1. Concatenation:
We can also use + operator to combine two
lists. This is also called
concatenation
>>> list1=[10,20,30]
>>> list1
[10, 20, 30]
>>> list1+[40,50,60]
[10, 20, 30, 40, 50, 60]
CONCATENATION EXAMPLE
>>> list2=[1.1,2.2,"Anna",78]
>>> list3=[1,2,3,4,5.5,"Diana"]
>>> list2+list3
[1.1, 2.2, 'Anna', 78, 1, 2, 3, 4, 5.5, 'Diana']
2. Repetition:
The * operator repeats a list for the given
number of times.
>>> list2 ['A', 'B']
>>> list2 *2
['A', 'B', 'A', 'B']
print(["re"] * 3)
#Output:
["re", "re", "re"]
3. slice:
This operation gives us character from given
index.Operator is symbolized using “[]”
brackets.
You can retrieve any element using this
operator.
>>> list2=[1.1,2.2,"Anna",78]
>>> list2[2]
'Anna'
4. Range slice or list slicing:
This operation return the characters from a
specified range.Operator is symbolized
using”[:]” sign.You can retrieve range of the
elements using this operator.
>>> list3=[1,2,3,4,5.5,"Diana"]
>>> list3[1:3]
[2, 3]
5. Membership:
>>> list=[1,2,3,4,"Anna"]
>>> 2 in list
True
>>> 5 in list
False
6 EXPLAIN INDEXING AND SLICING IN LIST WITH EXAMPLE INDEXING:
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40
WRITE BASIC OPERATIONS OF LIST
1)Accessing values in list:
To access values in lists, use the square
brackets for slicing along with the index or
indices to obtain value available at that index.
Example: accessing list values.
>>> list1 = ["one","two",3,10,"six",20]
>>> list1[0]
'one'
2) Deleting Values in List
The pop() method in Python is used to remove
a particular item/element from the given
index in the list. The pop() method removes
and returns the last item if index is not
Provided
>>> list[10, 20, 40]
>>> list.pop()
40
We can delete one or more items from a list
using the keyword del. It can even delete
the list entirely. But it does not store the value
for further use
>>> list= [10, 20, 30, 40]
>>> list
[10, 20, 30, 40]
>>> del (list[1]) # del() with index
>>> list
[10, 30, 40]
The remove() method in Python issued to
remove a particular element from the list. We
use the remove() method if we know the item
that we want to remove or delete from the
list (but not the index).
>>> list=[10,"one",20,"two"]
>>> list.remove(20)
>>> list
[10, 'one', 'two']
3. Updating Lists: • List are mutable, meaning their
elements can be changed or updated unlike string or
tuple.
We can update items of the list by simply assigning the
value at the particular index
position. We
can also remove the items from the list using remove()
or pop() or del statement.
>>> list1= [10, 20, 30, 40, 50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1[0]=0 # change 0th index element
>>> list1
[0, 20, 30, 40, 50]
4 Indexing
There are various ways in which we can access
the elements of a list.
List Index: We can use the index operator [] to
access an item in a list. Index starts
from 0. So, a list having 5 elements will have
index from 0 to 4.
Example:
>>> list1=[10,20,30,40,50]
>>> list1[0]
10
5. List Slicing
The slicing operator returns a subset of a list
called slice by specifying two indices, i.e.
start and end.
Syntax:
List_variable[start_index:end_index]
Example:
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]
LIST SLICING WITH STEP INDEX
Syntax:
list_name[start_index:end_index:step_size]
Ex.
list1=['red',1,'yellow',2,'green',3,'blue',4]
print(list1)
list2=list1[0:6:2]
print(list2)
#output:
['red', 1, 'yellow', 2, 'green', 3, 'blue', 4]
['red', 'yellow', 'green']
COMPLEX EXAMPLE OF LIST SLICING
>>> list1=[10,20,30,40,50]
>>> list1
[10, 20, 30, 40, 50]
>>> list1[::-1]
[50, 40, 30, 20, 10]
>>> list1[-1:-6:-1]
[50, 40, 30, 20, 10]
TRAVERSING A LIST
🞆 Accessing all elements of the List.
🞆 It can be done by any conditional statement of
python,but it is preferable to use for loop.
🞆 Example1
List1=[10,20,30,40]
for x in List1:
print(x)
Output:
10
20
30
40
EX:
🞆 Example2
List1=[10,20,30,40]
for i in range (len(List1)):
List1[i]=List1[i]+4
print(List1)
#Output
[14, 24, 34, 44]
EX:
list1=[[1,2,3,4],['A','B','C','D'],['@','#','$','&']]
for i in list1:
for j in i:
print(j,end=' ')
print('\n')
#output:
1234
ABCD
@#$&
METHODS OF LIST CLASS
1. list.append(item)
2. list.clear()
3. list.copy()
4. list.count(item)
5. list.extend(seq)
6. list.index(item)
7. list.insert(index,item)
8. list.pop(item)
9. list.remove(item)
10.list.reverse()
11.list.sort()
1.APPEND() METHOD
Example
List1=[10,20,30,40]
List1.append(50)
print(List1)
Output
[10, 20, 30, 40, 50]
2.CLEAR() METHOD
List.copy()
🞆 Example
List1=[10,20,30,40]
List2=List1.copy()
print(List2)
Output
[10, 20, 30, 40]
4.COUNT() METHOD
List.extend(Sequence)
Sequence can be List,Tuple,Set etc
🞆 Example
List1=[10,20,30,40]
List2=[50,60]
List1.extend(List2)
print(List1)
Output
[10, 20, 30, 40, 50, 60]
6.INDEX() METHOD
🞆 Ouptut
2
7. INSERT() METHOD
>>> List1.sort(reverse=False)
>>> List1
#output
[10, 20, 30, 40]
BUILT-IN FUNCTION
1. len(list)
2. max(list)
3. min(list)
4. sum(list)
1. LEN() METHOD
🞆 It returns the number of elements in the list.
🞆 Syntax
len(List)
🞆 Example
List1=[10,20,30,40]
x=len(List1)
print(x)
🞆 Output
4
2. MAX()
It returns the item that has the maximum
value in list.
Syntax:
max(list)
Example
List1=[10,20,30,40]
max(List1)
#Output:
40
3. MIN() METHOD
It returns the item that has the maximum
value in list.
Syntax:
min(list)
Example
List1=[10,20,30,40]
min(List1)
#Output:
10
4. SUM()
Calculate sum of all the elements of list.
Syntax:
sum(list)
Example
List1=[10,20,30,40]
sum(List1)
#Output:
100
1.Write the output of the following
>>> a=[2,5,1,3,6,9,7]
>>> a[2:6]=[2,4,9,0]
>>> print(a)
2.
>>> b=[“Hello”,”Good”]
>>> b.append(“python”)
>>>print(b)
3.
>>>t1=[3,5,6,7]
>>>print(t1[2])
>>>print(t1[-1])
>>>print(t1[2:])
>>>print(t1[:])
OUTPUT
Output:
1. [2, 5, 2, 4, 9, 0, 7]
2. ['Hello', 'Good', 'python']
3. >>>6
>>>7
>>>[6, 7]
>>>[3, 5, 6, 7]
WRITE PYTHON CODE FOR FINDING
GREATEST AMONG FOUR NUMBERS
list1 = [ ]
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
element = int(input("Enter elements: "))
list1.append(element)
print("Largest element is:", max(list1))
#output:
Enter number of elements in list: 4
Enter elements: 3
Enter elements: 6
Enter elements: 7
Enter elements: 2
Largest element is: 7
Tuples
TUPLES
🞆 A tuple is a collection which is ordered and
unchangeable.
🞆 The difference between the two is that we
cannot change the elements of a tuple once
it is assigned whereas, in a list, elements can
be changed.
🞆 In Python tuples are written with round
brackets whereas List are written in Square
brackets.
CREATING A TUPLE
🞆 A tuple is created by placing all the items
(elements) inside parentheses (), separated by
commas.
🞆 A tuple can also be created without using
parentheses. This is known as tuple packing.
🞆 A tuple can have any number of items and they
may be of different types (integer, float, list,
string, etc.).
🞆 The empty tuple is written as two parentheses
containing nothing
Tuple1=()
🞆 To write a tuple containing a single value you have
to include a comma, even though there is only one
value Tuple1=(10,)
🞆 Example
tuple1=(10,20,30,40)
tuple2=50,60,70
tuple3=()
tuple4=(80,)
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
Output:
(10, 20, 30, 40)
(50, 60, 70)
()
(80,)
>>> vijay=(11,'vijay','thane')
>>> (id,name,city)=vijay
>>> id
11
>>> name
'vijay'
>>> city
'thane'
>>> launge=('python','java')
>>> launge
('python', 'java')
>>> (a,b)=launge
>>> a
'python'
>>> b
'java'
SWAPPING THE VALUES OF TWO VARIABLES
USING TUPLE ASSIGNMENT
>>> x=10
>>> y=20
>>> (x,y)
(10, 20)
>>> x,y=y,x
>>> (x,y)
(20, 10)
ACCESSING VALUES IN TUPLES
tuple1 = ('p','e','r','m','i','t')
print(tuple1[-1])
print(tuple1[-5])
Output:
t
e
SLICING
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:7])
print(my_tuple[7:])
print(my_tuple[:])
#Output
('r', 'o', 'g')
('p', 'r', 'o', 'g', 'r', 'a', 'm')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
UPDATING TUPLES
>>> t1=(10,20,30,40,'a')
>>> 'a' in t1
True
>>> 20 in t1
True
3. Iterating through a tuple:
Iteration over a tuple specifies the way which the loop can be applied to the tuple.
Using a for loop we can iterate through each item in a tuple.following example uses
a for loop to simply iterates over a tuple.
t1=(10,20,30,'a',40)
for i in t1:
print(i)
#output:
10
20
30
a
40
for x in (1,2,3):
print(x)
1
2
3
🞆 Example
🞆 Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and
slicing work the same way for tuples as they
do for strings. Assuming following input −
L=(‘spam’,’Spam’,’SPAM!’)
BUILT-IN TUPLE FUNCTIONS
Function Description
len(tuple1) Returns the length of a tuple
max(tuple1) Returns item from the tuple
with max value.
min(Tuple) Returns item from the tuple
with min value.
tuple(sequence) Converts a list into tuple.
Zip(tuple1,tuple2) Zip elements from two tuples into a
list of tuples
count() Returns the number of
occurrences of a given element
in the tuple.
index(x) Returns the index of the first item
that is equal to x
LEN()
🞆 Python tuple method len() returns the
number of elements in the tuple.
🞆 Syntax
len(tuple)
🞆 Example
tuple1=(10,20,30,"amit",50)
print("Length=",len(tuple1))
🞆 Output
Length= 5
MAX()
🞆 Python tuple method max() returns the elements from the
tuple with maximum value.
🞆 Syntax
max(tuple)
🞆 Example
tuple1=(10,20,30,80,50)
tuple2=("Tiger","Lion","Dog","Zebra","Cat")
tuple3=("Tiger","Lion","Dog","Zebra","Zfbra")
print("Max value in Tuple=",max(tuple1))
print("Max value in Tuple=",max(tuple2))
print("Max value in Tuple=",max(tuple3))
🞆 Output
#output:
[(10, 'Tiger'), (20, 'Lion'), (30, 'Dog'), (80, 'Zebra'), (50, 'Cat')]
a=[(10, 'Tiger'), (20, 'Lion'), (30, 'Dog'), (80, 'Zebra'), (50,
'Cat')]
>>> tup1=(1,2,3)
>>> tup2=('A','B','C')
>>> tup3=zip(tup1,tup2)
>>> list(tup3)
[(1, 'A'), (2, 'B'), (3, 'C')]
DIFFERENCE BETWEEN LIST AND
TUPLE IN PYTHON:
Sr. No List Tuple
1 List is ordered and mutable data Tuple is ordered and immutable data
structure structure
2 List is represented with the square Tuple is represented with the round
brackets [ ] separated by commas.Ex. brackets () separated by commas.Ex.
List1=[1,2,3,4] T1=(1,2,3,4)
4 List supports more built-in methods. Tuple supports less built-in methods.
>>> s=set('abc')
>>> s
{'c', 'b', 'a'}
>>> s=set(range(1,3))
>>> s
{1, 2}
ACCESSING VALUES IN SET
🞆 You cannot access items in a set by referring
to an index, since sets are unordered the
items has no index.
🞆 But you can use loop to access the elements
or ask if a specified value is present in a set,
by using the ‘in’ keyword.
EXAMPLE
set1={10,20,30,40}
for x in set1:
print(x)
print("wheather 20 is present or not",20 in
set1)
Output:
40
10
20
30
wheather 20 is present or not True
s1={'A','B','C','D'}
for val in s1:
print(val)
#output:
D
A
B
C
HOW TO CHANGE A SET IN PYTHON OR
UPDATE A SET ?
Syntax:
A.add(element)
set1={10,20,30,40}
set1.add(50)
print(set1)
>>> a={1,2,3,4}
>>> a.add(6)
>>> a
{1, 2, 3, 4, 6}
Syntax:
A.update(B)
where B can be lists/strings/tuples/sets
set1={10,20,30,40}
set1.update([40,70,80],{90,60,20})
print(set1)
Output
{70, 40, 10, 80, 50, 20, 90, 60, 30}
>>> a={1,2,3}
>>> b={'a','b','c'}
>>> a
{1, 2, 3}
>>> b
{'c', 'b', 'a'}
>>> a.update(b)
>>> a
{1, 2, 3, 'a', 'c', 'b'}
>>> a.update({3,4})
>>> a
{1, 2, 3, 4, 'a', 'c', 'b'}
HOW TO REMOVE ELEMENTS FROM A SET?
set1.clear()
print(set1) set()
>>> b={'a','b','c'}
>>> b
{'c', 'b', 'a'}
>>> b.discard('b')
>>> b
{'c', 'a'}
>>> b.remove('a')
>>> b
{'c'}
>>> b={'a','b','c'}
>>> b.pop()
'c'
>>> b.pop()
'b'
>>> b={'a','b','c'}
>>> b.clear()
>>> b
set()
BASIC SET OPERATION
🞆 Sets can be used to carry out mathematical
set operations like union, intersection,
difference and symmetric difference
🞆 Set operations are as Follow
Set Union
Set Intersection
Set Difference
Set Symmetric Difference
SET UNION
Output
{1, 2, 3, 4, 5, 6}
{4, 5, 6, 7, 8}
CLEAR()
🞆 The clear() method removes all elements in a
set.
🞆 Syntax
🞆 set.clear()
🞆 Example
A = {1, 2, 3, 4, 5}
A.clear()
print(A)
output
Set()
COPY()
🞆 The copy() method copies the set.
🞆 Syntax
🞆 set.copy()
🞆 Example
A = {1, 2, 3, 4, 5}
B=A.copy()
print(B)
🞆 Output
{1, 2, 3, 4, 5}
DIFFERENCE_UPDATE()
OUTPUT
{1, 2, 3}
INTERSECTION_UPDATE()
🞆 The intersection_update() method removes
the items that is not present in both sets (or
in all sets if the comparison is done between
more than two sets).
🞆 The intersection_update() method is different
from the intersection() method, because the
intersection() method returns a new set,
without the unwanted items, and the
intersection_update() method removes the
unwanted items from the original set.
🞆 Syntax
🞆 set.intersection_update(set1, set2 ... etc)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
A.intersection_update(B)
print(A)
OUTPUT
{4, 5}
ISDISJOINT()
set.issuperset(set)
🞆 Example
A = {4, 5,3}
B = {4, 5,6,7,8}
C=A.issuperset(B)
print(C)
🞆 Output
False
SYMMETRIC_DIFFERENCE_UPDATE()
🞆 set.symmetric_difference_update(set)
🞆 Example
A = {3,4, 5}
B = {4, 5,6,7,8}
A.symmetric_difference_update(B)
print(A)
Output
{3, 6, 7, 8}
Write python program to perform following
operations on Set (Instead of
Tuple)-06Marks
i) Create set
ii) Access set Element
iii) Update set
iv) Delete set
# To Create set
S={10,20,30,40,50}
# To Access Elements from set
print (S)
#To add element into set using add method
S.add(60)
print(S)
#To update set using update method
S.update(['A','B'])
print(S)
#To Delete element from Set using discard()
method
S.discard(30)
print(S)
#To delete element from set using remove()
method
S.remove('A')
print(S)
#To delete element from set using pop()
method
S.pop()
print(S)
output:
{50, 20, 40, 10, 30}
{50, 20, 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60, 30}
{'B', 50, 20, 'A', 40, 10, 60}
{'B', 50, 20, 40, 10, 60}
{50, 20, 40, 10, 60}
USING TUPLES
🞆 #To create tuple
🞆 tuple1=(10,20,30,40,50)
🞆 print (tuple1)
🞆 #Access tuple values
🞆 print (tuple1[1])
🞆 print (tuple1[0:3])
🞆 # deleting tuple
🞆 del tuple1
🞆 print (tuple1)
output:
(10, 20, 30, 40, 50)
20
(10, 20, 30)
Traceback (most recent call last):
File "C:\Users\Vijay Patil\AppData\Local\
Programs\Python\Python310\temp.py", line
9, in <module>
print (tuple1)
NameError: name 'tuple1' is not defined. Did
you mean: 'tuple'?
Dictionary
DICTIONARY
#Output:
Amit
20.54
Traceback (most recent call last):
File "E:/prg/Dict.py", line 4, in <module>
print(Dict1[4])
KeyError: 4
UPDATING DICTIONARY
#Output
{1: 20, 2: 'Rohan', 3: 20.54}
{1: 20, 2: 'Rohan', 3: 20.54, 4: 'Amol'}
HOW TO DELETE OR REMOVE ELEMENTS
FROM A DICTIONARY?
Output
Amit
None
40
ITEMS()
Output
dict_keys([1, 2, 3, 4])
dict_keys([1, 2, 3, 4, 5])
POP()
🞆 The pop() method removes the specified item
from the dictionary.
🞆 The value of the removed item is the return
value of the pop() method,
🞆 Syntax
dictionary.pop(keyname, defaultvalue)
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict1.pop(2)
print(Dict1)
element=Dict1.pop(5,'Amar')
print(element)
Dict1.pop(6)
print(Dict1)
Output
{1: 20, 3: 20.54, 4: 'Amol'}
Amar
Traceback (most recent call last):
File "E:\prg\Dict.py", line 6, in <module>
Dict1.pop(6)
KeyError: 6
POPITEM()
🞆 The popitem() method removes the item that was last
inserted into the dictionary. In versions before 3.7, the
popitem() method removes a random item.
🞆 The removed item is the return value of the popitem()
method, as a tuple
🞆 Syntax
dictionary.popitem()
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
element=Dict1.popitem()
print(element)
🞆 Output
(4, 'Amol')
SETDEFAULT()
🞆 The setdefault() method returns the value of
a key (if the key is in dictionary). If not, it
inserts key with a value to the dictionary.
🞆 Syntax
dictionary.setdefault(keyname, default_value)
🞆 The setdefault() takes maximum of two
parameters:
key - key to be searched in the dictionary
default_value (optional) - key with a value
default_value is inserted to the dictionary if key
is not in the dictionary.
If not provided, the default_value will be None.
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.setdefault(2))
element=Dict1.setdefault(5,'Amar')
print(element)
print(Dict1)
Output
Amit
Amar
{1: 20, 2: 'Amit', 3: 20.54, 4: 'Amol', 5: 'Amar'}
UPDATE()
🞆 The update() method adds element(s) to the
dictionary if the key is not in the dictionary. If
the key is in the dictionary, it updates the
key with the new value.
🞆 Syntax
dictionary.update(iterable)
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
Dict2={2:50}
Dict1.update(Dict2)
print(Dict1)
Dict3={5:90}
Dict1.update(Dict3)
print(Dict1)
🞆 Output
{1: 20, 2: 50, 3: 20.54, 4: 'Amol'}
{1: 20, 2: 50, 3: 20.54, 4: 'Amol', 5: 90}
VALUES()
🞆 Example
Dict1={1:20,2:'Amit',3:20.54,4:'Amol'}
print(Dict1.values())
Output
dict_values([20, 'Amit', 20.54, 'Amol'])
COMPARE LIST AND DICTIONARY
🞆 Write a program to create dictionary of
student the includes their ROLL NO and
NAME
🞆 i) Add three students in above dictionary
🞆 ii) Update name=’Shreyas’ of ROLL NO=2
🞆 iii) Delete information of ROLL NO=1
1)
>>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
>>>print(dict1)
{1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}
ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}
iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}
End