data structures in python: List, tuple, set, dictionaries
AshaWankar1
64 views
108 slides
Jun 02, 2024
Slide 1 of 108
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
About This Presentation
This PPT provides various data structures in Python such as lists, tuples, sets, and dictionaries with methods and operations. python, list, list(), data, data structure, dictionary,dictionary(), tuple(), insert, insert(), sorted, sorted(), dict(), del, del(), sum(), sum, len, len(), append, append(...
This PPT provides various data structures in Python such as lists, tuples, sets, and dictionaries with methods and operations. python, list, list(), data, data structure, dictionary,dictionary(), tuple(), insert, insert(), sorted, sorted(), dict(), del, del(), sum(), sum, len, len(), append, append(), extend, extend(), index, index(), length, length(), remove, remove(), sort, sort(), reverse, reverse(), copy, copy(), clear, clear(), min, min(), max, max(), list comprehension, unpack, unpacking, slice, cut, count, count(), built-in, zip, zip(), unzip, unzipping, divmod, divmod(), create, create(), any, any(), all, all(), update, update() clear, clear(), discard, discard(), pop, pop(),union, union(), intersection, intersection(), intersection_update, intersection_update(), difference,difference() difference_update, difference_update(), symmetric_difference,symmetric_difference() symmetric_difference_update, symmetric_difference_update(), return, issubset, issubset(), is subset, issuperset, is superset, issuperset(), key, keys(), value, values(),operations, operation, NameError, fromkeys, fromkeys(), get, get(), items, items(), keys, pop, pop(), popitem, popitem(), setdefault, setdefault() nested, nested dictionaries, nested list, nested sets
Size: 14 MB
Language: en
Added: Jun 02, 2024
Slides: 108 pages
Slide Content
DATA STRUCTURES IN PYTHON
BY -
MS. A. V. WANKAR
MRS. DIPALI GOSAVI
PREAMBLE
In this teaching material readers will understand:-
1. What are the different data structures in python
2. What are the methods of each data structure.
3. What operations can be performed on each data
structure.
. Applying data structures to solve the problems.
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
SBATA’STRUCTURES IN PYTHON
1. List
2. Tuple
3. Set
4. Dictionary
lists can be heterogeneous
* a = [hello', example‘, 100, 1234, 2*2]
Lists can be indexed and sliced:
- a[O] -> hello”
* a[:2] -> [hello', 'example']
Lists can be manipulated
* a[2] = a[2] + 23
* a[0:2] = [1,12]
- a[0:0] = |]
elen(a) -> 5
= It is possible to create a new list from another.
" Example:
® A=[1,34.5,’hello’,2+3j]
= B=A # copies all elements of A to B, both points to
same list, Changing one changes the other.
" It is possible to create a list of lists:
" Example:
" A=/1,2,3,4]
= B=[10,20,A,30]
= Print(B) # [10,20,[1,2,3,4],30]
= It is possible to unpack a list within a list using the
* operator.
" Example:
" A=/1, 2, 3,4]
= B=[10,20,*A,30]
HE] = Print(B) # [10,20,1,2,3,4,30]
vata structures in Python
LIST METHODS
=" append(x): append element x at the end of list & does
not return anything. i.e. None is returned
" Syntax: list. append (x)
= Example:
+ # Adds List Element as value of List.
+ List = [Mathematics', 'chemistry', 1997, 2000]
» List.append(20544)
vata structures in Python
" extend(List2): append all items in List2 to list 1, returns
None.
" Syntax: List1.extend(List2)
= Example:
*List1 = [1, 2, 3]
-List2 = [2, 3, 4, 5]
++ Add List2 to List1
-Listl.extend(List2)
-print(List1)
«+ Add List1 to List2 now
“fg ist2.extend(List1)
vata structures in Python
LIST METHODS
= insert(i, x): Insert element x at index i (i should be
within range , otherwise we get Index Error ), returns
None.
" Syntax: list.insert(index, x)
" Example:
-List = Mathematics”, ‘chemistry’, 1997, 2000]
++ Insert at index 2 value 10087
*List.insert(2, 10087)
-print(List)
vata structures in Python
COPYRIGHT
sc
Date 091 4
count(x): Returns total occurrence of element x in List
" index(x) : Returns the index of first occurrence of x
" Syntax: List.index(x[,start][,end])
=" Example:
«List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
*print(List.index(2))
“Print(List.index(2,2))
El ?rint(List.index(2,5,9) # it will search in start=5 and end=9-1
€ “es
vata structures in Python
" pop([index]) : Index is not a necessary parameter, if not
mentioned pops and returns element at the last index.
= Example:
= List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
= Print(List.sort())
= #Reverse flag is set True
HE] List.sort(reverse=True)
vata structures in Python
clear(): It simply reverses the list, returns None.
= Syntax: List.clear()
= Example:
" List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
= List.clear()
= print(List}# prints empty list
= copy() : copy elements of List. Returns List
= Syntax: List.copy()
= Example:
" List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
El L-List. copy()
vata structures in Python
ING ELEMENT USING DEL
del list[index]: Element to be deleted is mentioned using list
name and index. remove by index, not value remove slices from
list (rather than by assigning an empty list)
" Syntax: del list/index] or del list/start_index : end_index]
= Example:
= List =[2.3, 4.445, 3, 5.33, 1.054, 2.5]
= del List/O]
= del List[3:5] # removes elements from index start to end-1
= Print(List)
vata structures in Python
N FUNCTIONS OF LIST
=" sum() : Calculates & Returns sum of all the elements of List.
= Syntax: sum(List)
" Example:
« List =[1, 2, 3, 4, 5]
= print(sum(List))
= Note: Sum is calculated only for Numeric values, elsewise
throws TypeError.
= len() :Calculates & Returns total length of List.
" Syntax: len(list_name)
" Example:
E List ™ [1,.2,-3).1, 2, 1,2,3,2, 1]
print (List)
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
N FUNCTIONS OF LIST
"= min() : Calculates & Returns minimum of all the elements of
List.
" max() :Calculates 8 Returns maximum of all the elements of
List.
= Syntax: max(List)
ıple:
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
N FUNCTIONS OF LIST
= sorted() : returns a sorted list of the specified list.
" Syntax: sorted(list[,key/, Reverse_Flag ] |)
" Example:
" List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]
= l1=sorted(List)
= Print(l1)
" 12=sorted(List, reverse=True)
" Print(l2)
Note: if Reverse_Flag = True then sorts in descending order
atherwise sort in ascending order, by default Reverse_Flag = False.
vata structures in Python
COPYRIGHT
NEW DE
Reg. No.
L() BUILT-IN FUNCTIONS
= This function returns true if all of the items are True (or if
the iterable is empty).
= All can be thought of as a sequence of AND operations on the
provided iterables.
" Syntax: all(list of iterables)
= Example:
= # print (all([True, True, True, True])) # Here all the iterables are
True so all will return True and the same will be printed
= Items can be of mixed types, including
collection types.
" tuples are defined using parentheses and
commas.
= Example:
t = (23,‘abc’,4.56,(2,3), xyz’)
" individual members of a tuple are accessed by
using positive and negative index starting with
‘0’ similar to the lists.
Example:
print(t[O]) # prints 23
“ print(t[-1]) # prints ‘xyz’
vata structures in Python
FOPLES: DEFINING TUPLES
=" Using parenthesis to define tuple is optional.
"= Example:
a=10;b=20;c=30
t=a, b,c
or
t=(a, b, c)
print(t)
=" Empty tuple can be created as shown below.
=» Example:
t=()
print(t)#()
= A tuple with single value can be created as..
= Example:
t=(23,)
te: note the comma (,) written after 23. If we
n'tgive this comma then t will be created as a
rmal variable instead of tuple.
im Python
: UNPACKING
" Itis possible to unpack tuples & also lists.
= Example:
a=t[0]
b=t|1]
c=t[2]
(a, b, c)=t
or
a, b, c=t
« Ifthe number of variables are less than the
number of values then we can add an * to the
variable name and the values will be assigned
to the variable as a list:
: Examplel:
= (23, ‘abc’,4.56,(2,3), xyz’)
: a. b, *c)=t
print(c)
" Itis possible to unpack tuple within another
tuple.
= Example:
t1=(100,*t)
print(t1) # (100,23,’abc’,4.56,(2,3),’xyz’)
NEW DELHI
TUPLES} SLICE/CUT OPERATOR ([:])
= We can use cut/slice operator ([:]) with tuples
similar to the lists.
"= Example:
t=(23,45,56.4,3+6j,’abc’)
print(t[2:])#(56.4,3+6j,’abc’)
= We can print all elements of tuple using cut/slice
operator ([:]) similar to lists.
=» Example:
t=(23,45,56.4,3+6j,’abc’)
print(t[:])#(23,45,56.4,3+6j,’abc’)
" Similar to the lists we can print tuple in a reverse
“ing cut/slice operator ([:])
Example:
«=(93,45,56.4,3+6j,'abc”
rint(t[: 1])#(23, 45,56.4,3+6j,’abc’)
COPYRIGHT OFFICE
LE VARIETIES
" It is possible to create a new tuple from another.
" Example:
= A=(1,34.5,’hello’,2+3})
= B=A # copies all elements of A to B, both points to same tuple.
= It is possible to create a tuple of tuple:
" Example:
" t1= (2, 5, 3)
" 12=(1,34,6)
" t3=(t1, t2)
- print{t3}#((2,5,3),(1,34,6))
€
vata structures in Python
RIETIES (CONT....)
" A tuple can be embedded in another tuple.
" Example:
= A=(1,2,3,4)
= B=(10,20,A,30)
= print(B) # (10,20,(1,2,3,4),30)
" Similar to lists, it is possible to concatenate two tuples.
= Example:
= A=(1,2,3,4)
" B=(10,20,30)
El C=A+B
ER à:
print(C}# (1,2,3,4,10,20,30)
vata structures in Python
= 1. t.count() : the count() method returns the number of
times a specified value appears in the tuple.
= Syntax:
t.count(value)# value is nothing but item to search
for in tuple t.
" Example:
t=(23,45,23,56.4,3+6j,’abc’)
print(t.count(23))#2
= 2. t.index() : Search for the first occurrence of the value 8
and return its position.
= Syntax:
t.index(value)# value is nothing but item to search
for in tuple t.
¿El Example:
92.15: 23,56.4,3+6j,’abc’)
vata structures in Python
ES: BUILT-IN FUNCTIONS
= 1. t.count() : the count() method returns the number of
times a specified value appears in the tuple.
= Syntax:
t.count(value)# value is nothing but item to search
for in tuple t.
" Example:
t=(23,45,23,56.4,3+6j,’abc’)
print(t.count(23))#2
= 2. t.index() : Search for the first occurrence of the value 8
and return its position.
= Syntax:
t.index(value)# value is nothing but item to search
for in tuple t.
¿El Example:
@ 3,45,23,56.4,3+6j,’abc’)
“print(t. index(23))#0
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
N FUNCTIONS OF TUPLE
=" sum() : Calculates & Returns sum of all the elements of
tuple.
= Syntax: sum(t)
" Example:
" t=(1, 2, 3, 4, 5)
= print(sumft))
"= Note: Sum is calculated only for Numeric values, elsewise
throws TypeError.
= It returns False if empty or all are false. Any can be thought
of as a sequence of OR operations on the provided iterables.
= Syntax: any(list of iterables)
" Example:
= # print (any((False, False, False, False))) # Here all the
iterables are False so any will return False and the same will
" The zip() function returns a zip object, which is an
iterator of tuples where the first item in each passed
iterator is paired together, and then the second item in
each passed iterator are paired together and so on .....
" Syntax: zip(*iterables) # can be anything like lists,
tuples etc.
= If we do not pass any parameter, zip() returns an empty
iterator.
" Ifa single iterable is passed, zip() returns an iterator of
tuples with each tuple having only one element.
passed iterators have different lengths, the
the least items decides the length of the
" Create 3 lists - a list of names, a list of ages, a list
of salaries. Generate and print a list of tuples
containing name, age and salary from the 3 lists.
From this list generate 3 tuples — one containing
all names, another containing all ages and third
containing all salaries.
name _tuple, age _tuple, salary_tuple=zip(*l)
print(name_tuple)
print(age_tuple)
print(salary_tuple)
vata structures in Python
(GSLEM STATEMENT: 02
" Create a list of tuples. Each tuple should contain
an item and its price in float. Write a program to
sort the tuples in descending order by price.
vata structures in Python
= divmod() function takes two argument and return
the tuple of quotient and the reminder.
= Examplel:
Result=divmod(17,3)
print(Result)
= Example2:
t=(17,3)
R=divmod(*t)
RACTICE QUESTIONS:
a) Write a program to obtain transpose of a 3x4
matrix using zip().
b) Write a program to multiply two matrices x(2x3)
and y(2x2) using list comprehension and zip
function.
c) Suppose we have a list of 5 integers and a tuple of
5 floats. Can we zip them and obtain an iterator.
If yes, how ?
d) Write a program to unzip a list of tuples into
individual lists
= "pose a date is represented as a tuple (d, m, y).
Lea program to create 2 date tuples and find
nutaber of days between the two dates.
vata structures in Python
COPYRIGHT OFFICE
N
„ASSIGNMENT NO: 03
Date 08)
Store the data about shares held by a user as tuples
containing the following information about shares.
Share name
Date of purchase
Cost price
Number of shares
Selling price
Write a program to determine:
a) Total cost of portfolio
BansE ll amount gained or lost.
¿ :entägé-profit made or loss incurred.
vata structures in Python
CE
SEE-IN PYTHON: INTRODUCTION
" A set is an unordered collection of items which are
separated by comma (,) and enclosed in curly
brackets ({}).
= Items of a set can be of any data type.
= set do not contain duplicate values
= Example:
A={20} # set with 1 value.
B={abc’,34,7+3j,90.45} # set with multiple items.
C={10,10,10,10} # only 1 10 gets stored.
vata structures in Python
THON: INTRODUCTION (CONT...)
" Set is an unordered collection; hence order of
insertion is not same as the order of access.
=" Example:
A={15,25,35,45,55}
print(A) # doesn’t always print {15,25,35,45,55}
= The elements in the set are immutable(cannot be
modified) but the set as a whole is mutable i.e. We
can add or remove items from it.
vata structures in Python
THON: INTRODUCTION (CONT....)
= A set() function can be used to convert a string, ,
list or tuple into a set.
“ll :: While creating set using set(), repetitions are
vata structures in Python
EMPTY SET
"= Empty set can be created by using a set()
constructor.
" Example:
S=4 # It will create empty dictionary
S=set() # It will create empty set
= Note: It is not possible to create empty set by
using { , instead it creates empty dictionary. To
create empty set, we must use set() constructor.
vata structures in Python
CESSING SET ELEMENTS:
eing an unordered collection, items in a set
cannot be accessed using indices.
" Sets can not be sliced using [|].
= Entire set can be printed by just using the name of
the set.
= Example:
S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}
" Like strings, lists and tuples, sets can be iterated
over, using a for loop.
=" Example:
„m >={10, 20, 30, 40, 50}
print(i)
vata structures in Python
creating sets
Example:
S={10, 20, 30, 40, 50} #{30, 20, 10, 40, 50}
= We can use membership operator with set as
Example:
S=(10, 20, 30, 40, 50}
print(12 in S) # False
print(12 not in S) # True
= Set can be deleted by using del keyword
Example:
S={10, 20, 30, 40, 50}
del S
print(S) # NameError
le]
vata structures in Python
COFYRIG!
"EXAPERATIONS: (CONT...)
is possible to unpack a set within using *.
= sorted() : returns a sorted list of the specified set.
= Syntax: sorted(set_name/,key/, Reverse_Flag ] |)
" Example:
= s = (2.3, 4.445, 3, 5.33, 1.054, 2.5}
= 11=sorted(s)
" print(l1)
" 12=sorted(s, reverse=True)
= print(l2)
Note: if Reverse_Flag = True then sorts in descending order
atherwise sort in ascending order, by default Reverse_Flag = False.
vata structures in Python
COPYRIGHT
NEW DE
Reg. No.
L() BUILT-IN FUNCTIONS
= This function returns true if all of the items are True (or if
the iterable is empty).
= All can be thought of as a sequence of AND operations on the
provided iterables.
" Syntax: all(s)
= Example:
= # print (all({True, True, True, True})) # Here all the iterables
are True so all will return True and the same will be printed
= print (all({False, True, True, False})) # False
E] print (all({False, False, False})) # False
vata structures in Python
COPYRIGHT
NEW DE
Reg. No.
() BUILT-IN FUNCTIONS
= Returns true if any of the items is True.
= It returns False if empty or all are false. Any can be thought
of as a sequence of OR operations on the provided iterables.
= Syntax: any(s)
" Example:
= # print (any({False, False, False, False})) # Here all the
iterables are False so any will return False and the same will
be printed
= print (any({False, True, False, False})) # True
print (any({True, False, False, False})) # True
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
TIONS/METHODS
=" add(ele):
= If we want to add a single element to an existing set, we can
use the .add() operation.
= It adds the element to the set and returns 'None'.
= If the element already exists then add() method do not add
an element.
= Syntax: s.add(ele) # adds element ele to set s
= Example:
S={10, 20, 89, 09}
S.add(100)
print(S) # {10, 89, 09, 100, 20}
».add(10)
: {10, 89, 09, 100, 20}
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
TIONS/METHODS
=" update(seq):
= If we want to add a sequence of items then we use it.
= seq can ba list, tuple , set or dictionary(If seq is dictionary
then only keys will be added to set & not values).
= It adds the elements of seq to the set and returns 'None'.
"If the elements of seq already exists then .update() method
do not add the elements.
" Syntax: s.update(seq) # adds elements of seq to set s
= Example:
S={10, 20, 89, 09}
S.update([100,200])
rint(S) # (10, 89, 09, 100, 20}
update((12, 13))
rint(Sj'#{10, 89, 09, 100, 20,13,12}
vata structures in Python
TIONS/METHODS
= This method removes all elements of a set and return None.
= Syntax: s.clear() # removes all elements of set s
= Example:
S=(10, 20, 89, 09}
S.clear()
print(S) # set()
print(s.clear()) # None
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
TIONS/METHODS
= This method removes element ele from the set.
= If element does not exist, it raises a KeyError.
" The method returns None.
" Syntax: s.remove(ele) # removes element ele of set s
" Example:
S={10, 20, 89, 09}
S.remove(20)
print(S) # {10, 89, 09}
print(s.remove(10)) # None
print(s.remove(20)) # KeyError is raised
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
TIONS/METHODS
= discard(ele):
= This method also removes element ele from the set.
= If element does not exist, it does not raise a KeyError.
The method returns None.
= Syntax: s.discard(ele) # removes element ele of set s
= Example:
S={10, 20, 89, 09}
S.discard(20)
print(S) # {10, 89, 09}
print(s.discard(10)) # None
print(s.discard(20)) # KeyError not raised
vata structures in Python
COPYRIGHT OFFICE
NEW DELHI
TIONS/METHODS
= This operation removes and return an arbitrary element
from the set.
= If there are no elements to remove, it raises a KeyError.
= Syntax: s.pop() # removes arbitrary element of sets
= Example:
S={10, 20, 89, 09}
S.pop() # arbitrary element is popped and returned.
print(S) # arbitrary element which is popped
print(s.pop()) #
print(s.pop(20)) # KeyError raised
vata structures in Python
SETRFUNCTIONS/METHODS
= The copy() method returns a shallow copy of the set.
= Aset can be copied using = operator in Python.
= Example:
S=(2,35,79,0}
S1=S
print(S1)
S1.add(100)
print(S) + (85, 79, 0, 2, 100)
print(S1) # (35, 79, 0, 2, 100}
= Note: The problem with copying the set in this way is that if you modify the set S1,
the set S is also modified.
= Syntax: s.copy() # creates a shallow copy, changes made in shallow copy
do not change original set.
= This function returns length of the object.
= Syntax: object.__len__()
= Note: object can be a list, tuple, set or dictionary.
" Example:
S={2,35,79,0}
print(S._len__())
= Note: when we use dictionary as an argument to
union it will add key only in a union set.
= print(s | “Rank”)
= print(s | [‘R’, ’a a es n ? , K] )
ES
(s|£Rank”:1)
(s| {R’, a, n° k”)
vata structures ın P
COPYRIGHT OFFICE
MA TFEMATICAL OPERATIONS : INTERSECTION
Rel
Date 09/05/2024
= sl.intersection(s2) :
= The intersection() method returns the intersection of a
set and the set of elements in an iterable object s2.
"Sometimes, the & operator is used in place of
the intersection() method, but it only operates on
the set of elements in set.
= Syntax: sl.intersection(s2)# here s2 can be set, list,
tuple, dictionary
or
s1&s2 # here s2 must be set only.
" Example:
s1={0,1,2,6}
> $2={34,54,6}
“ print(s1.intersection(s2)) +6)
vata structures in Python
„MORE EXAMPLES ON INTERSECTION
acker”)
" print(s.intersection(“Rank”))
" print(s.intersection([R”,'a”,'n”,'k”))
= Print(s.intersection((‘R’,’a’,’n’,’k’))
= Print(s.intersection({*Rank”:1}))
= Note: when we use dictionary as an argument to
union it will add key only in a union set.
" This method update s1 with the intersection of
sl and s2 (iterable object) given in argument by
removing the items in s1 that are not present in
both sl and s2.
ATICAL OPERATIONS: SYMMETRIC_DIFFERENCE
etric_difference(s2) :
" Return a set that contains all items from both
sets, except items that are present in both sets:
= Sometimes the ‘ operator is used in place of
the symmetric_difference() , but it only operates on
the set of elements in set.
= Syntax: sl.symmetric_difference(s2) #here s2 can
be set, list, tuple, dictionary
or
s1/4s2 # here s2 must be set only.
" Example:
~>S1={2,4,5,0}
El >52=(5,0,9,8)
>pfäntf&Esymmetrci_difference(s2)) # (2,4,9,8)
vata structures in Python
GAL OPERATIONS : SYMMETRIC_DIFFERENCE_UPDATE
sl.symmetric_difference_update(s2) :
" This method update s1 with the
symmetric_difference()of sl and s2 ( iterable
object)
= Return True if all items in set s1 are present in set s2.
= Sometimes the <= operator is used in place of
the issubset() , but it only operates on the set of
elements in set.
= Syntax: sl.issubset(s2) #here s2 can be set, list,
tuple, dictionary
Or
sl<=s2
" Example:
>>s1={2,4,5,0}
~>s2={5,0,9,8}
>print(s1.issubset(s2)) + False
>s222455,0,9,8)
> print(s1.issubset(s2)) # True
vata structures in Python
COPYRIGHT OFFICE
TEMATICAL OPERATIONS: ISSUPERSET()
= Return True if all items in set s2 are present in set s1.
= Sometimes the >= operator is used in place of
the issuperset() , but it only operates on the set of
elements in set.
= Syntax: sl.issuperset(s2) #here s2 can be set, list,
tuple, dictionary
Or
sl>=s2
" Example:
>>s1={2,4,5,0}
~>s2={5,0,9,8}
>print(s1.issuperset(s2)) # False
>s F455}
> print(s1.issuperset(s2)) # True
vata structures in Python
COPYRIGHT OFFICE
HENSION
comprehensions, set comprehensions offer
an easy way of creating sets. It consists of braces
containing an expression followed by a for clause,
and zero or more for or if clauses.
=" General form of set comprehension is:
"s={ expression for var in sequence [optional for
and/or if] }
" Example:
a={x**2 for x in range(5) }
print(a) #
= »={num for num in a if num > 2 and num < 10}
| orint(b
ES
vata structures in Python
RY IN PYTHON : INTRODUCTION
= Python dictionary is mutable and an unordered collection of
items where each item of a dictionary has a key/value pair.
=" Each key is separated from its value by a colon (:).
" The items are separated by commas, and the whole thing is
enclosed in curly braces.
"= An empty dictionary without any items is written with just
two curly braces, like this: ÿ.
=" Keys are unique within a dictionary while values may not
be.
" The values of a dictionary can be of any type, but the keys
must be of an immutable data type such as strings,
numbers, or tuples.
ralues can be of any data type and can repeat, but keys
be_of immutable type (string, number or tuple with
itable elements) and must be unique.
vata structures in Python
ON ARY IN PYTHON : INTRODUCTION (CONT..)
Dictionary keys are case sensitive, same name
but different cases of Key will be treated distinctly.
ll Dict = (Name': XYZ’, 1: [1, 2, 3, 4}
4 pritt(\nDictionary with the use of Mixed Keys: ")
print(Dict)
vata structures in Python
COPYRIGHT OFFICE
CFONARY : ACCESSING ELEMENTS
While indexing is used with other data types to access
values, a dictionary uses keys.
=" Keys can be used either inside square brackets [] or with
the get() method.
= If we use the square brackets [], KeyError is raised in case a
key is not found in the dictionary.
" On the other hand, the get() method returns None if the key
is not found.
" Example:
= # get Vs [] for retrieving elements
d={name': ‘XYZ’, 'age': 26}
print(d[‘name']) # XYZ
print(d.get('age')) + 26
print(d.get('address'))#None
priftiál'address' ])#KeyError
vata structures in Python
RY : ITERATING USING FOR LOOP
ary can be iterated over in following ways:
d=(name' : 'XYZ', 'age' : 25, 'salary' : 3445}
for k in d:
print(k) # prints all keys of the dictionary
= Iterate over key-value pairs:
for x in d.items():
print(x) # prints tuples of key-value pair
for k, v in d.items():
print(k, v) # prints key-value pairs
" Iterate over keys:
for k in d.keys():
print(k) # prints keys
te over values:
Sin d.values():
print(v) # prints values
for
vata structures in Python
QNARY : OPERATIONS
We can change the value of a specific item by
referring to it’s key name.
= Example:
d={name' : 'XYZ', 'age' : 25, 'salary' : 3445}
d['salary']=10000
print(d)
= We can also check if key exists using membership
operator.
= Example:
d={name' : 'XYZ', 'age' : 25, 'salary' : 3445}
if 'age' in d:
_ print(Yes, age is one of the key in
à dictionary’)
vata structures in Python
ON ARY : DELETING KEY FROM DICTIONARY
using del keyword we can remove the item
with the specified key name.
= We can also delete the complete dictionary
using del keyword.
= Example:
d={name' : 'XYZ', 'age' : 25, 'salary' : 3445}
del d
2rint(d) # NameError: name 'd' is not defined
= 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: d.pop(key [,defaultValue]) #where d is
dictionary.
= Note: Optional. A value to return if the specified
key do not exist.
= Example:
orint(d.pop(8,’hello’))#eight
orint -pop(1,’hello’)) #hello
orint(d.pop(2))# KeyError
im Python
ARY : METHODS
Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
popitem(): method removes the item that was last
inserted into the dictionary.
The removed item is the return value of
the popitem() method, as a tuple
Syntax: d.popitem() #where d is dictionary.
Example:
print(d.popitem())#
ARY : METHODS
=" Consider, d={8:‘eight', 4:‘four', 9:‘nine'}
= setdefault(): The setdefault() method returns the value of the
item with the specified key.
" If the key does not exist, insert the key, with the specified
value.
= Syntax: d.setdefault(key [,value]) #where d is dictionary.
= Note: Value is Optional.
If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's value.
Default value None
General form is:
d={key:value for (key,value) in d.items()}
= Example:
d=fa’:1,’b’:2,’c’:3,’d’:4,’e’:5}
#Obtain dictionary with each value cubed
d1={k:v**3 for (k,v) in d.items()}
print(d1)#dictionary with each value cubed
#obtain dictionary with each value cubed if value>3
d2={k:v for (k,v) in d.items() if v>3}
print(d2)
*"Jentify odd and even entries in the dictionary
aol ={k:((EVEN’ if v%2==0 else ‘ODD’ for (k,v) in
ters ke
Dal
102
tionary Comprehension
" Create two lists' students and marks. Create a
dictionary from these two lists using dictionary
comprehension. Use names as keys and marks as
values.
= Answer:
Istnames=[‘Sunil’,’Anuj’,’Rahul’,’Anuja’,’Rohit’]
Istmarks=[54,65,45,67,78]
E ={k:v for (k,v) in zip(lstnames,lstmarks)}
“intid): .
ere A
Data Structures in Python
oblem Statement: 01
« Write a program that reads a string from
the keyboard and creates dictionary
containing frequency of each character
occuring in the string.
- oblem Statement: 02
" A sparse matrix is a matrix most of
whose elements have a value 0. Suppose
we have a 5x5 sparse matrix stored as a
list of lists. Dictionary should store the
row and column of a non-zero element
as a tuple key and the value of the non-
zero element as the value against the
key tuple.