MARUDHAR KESARI JAIN COLLEGE FOR WOMEN, VANIYAMBADI
PG DEPARTMENT OF COMPUTER APPLICATIONS
Subject Name : PYTHON PROGRAMMING
CLASS : I-BCA
SUBJECT CODE :23UCA11
UNITIV
Lists:Creating a list-Access values in List-Updating values in Lists-Nested lists-Basic list
operations-List Methods. Tuples:Creating,Accessing,Updatingand Deleting Elements in a tuple–
Nested tuples–Difference between lists and [Link]:Creating,Accessing,Updatingand
Deleting Elementsina Dictionary–Dictionary Functions And Method Difference between Listsand
Dictionaries.
A sequence is a datatype that represents a group of elements. The purpose of any
sequence is to store and process group elements. In python, strings, lists, tuples and
dictionaries are very important sequence datatypes.
LIST:
A list is similar to an array that consists of a group of elements or items. Just like an
array, a list canstore elements. But,there is one major difference betweenanarrayand a list. An
array can store only one type of elements whereas a list can store different types of elements.
Hence lists are more versatile and useful than an array.
Creatinga List:
Creating a list is as simple as putting different comma-separated values between
square brackets.
student=[556,“Mothi”,84,96,84,75,84]
We can create empty list without any elements by simply writing empty square
brackets as: student=[ ]
We can create a list by embedding the elements inside a pair of square braces []. The
elements in the list should be separated bya comma (,).
AccessingValuesin 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. To view the elements of a list as a whole, we
can simplypass the list name to print function.
Ex:
student =[556,“Mothi”,84,96,84,75,84] print
student
printstudent[0]#Access0thelement
printstudent[0:2]#Access0thto1stelements
print student[2:] #Access 2nd to end of list elements
print student[ :3] # Access starting to 2nd elements
printstudent[:]#Accessstartingtoendingelements print
student[-1] # Access last index value
printstudent[-1:-7:-1]#Accesselementsinreverseorder
Output:
[556,“Mothi”,84,96, 84,75, 84]
Mothi
[556,“Mothi”]
[84, 96,84, 75,84]
[556,“Mothi”, 84]
[556,“Mothi”,84,96, 84,75, 84]
84
[84,75,84,96,84,“Mothi”]
Creatinglistsusingrange()function:
Wecanuserange() functionto generateasequenceofintegerswhichcanbestoredin a list.
To store numbers from0 to 10 in a list as follows.
numbers=list(range(0,11))
printnumbers# [0,1,2,3,4,5,6,7,8,9,10]
Tostoreevennumbersfrom0to 10ina list asfollows.
numbers = list( range(0,11,2) )
printnumbers# [0,2,4,6,8,10]
Loopingon lists:
We can also display list byusing for loop (or) while [Link] len( ) function useful to
know the numbers of elements in the list. while loop retrieves starting from 0 th to the last
element i.e. n-1
Ex-1:
numbers=[1,2,3,4,5] for
i in numbers:
printi,
Output:
12345
Updatinganddeletinglists:
[Link] list. Wecanappend, update or
delete the elements of a list depending upon our requirements.
Appendinganelement meansaddinganelement attheendofthe [Link],appenda new
element to the list, we should use the append() method.
Example:
lst=[1,2,4,5,8,6]
print lst #[1,2,4,5,8,6]
[Link](9)
printlst #[1,2,4,5,8,6,9]
Updatinganelement meanschangingthevalueoftheelement inthe [Link] done
byaccessingthe specific element using indexing orslicingand assigning a new value.
Example:
lst=[4,7,6,8,9,3]
printlst #[4,7,6,8,9,3]
lst[2]=5 #updates2ndelementinthelist
print lst # [4,7,5,8,9,3]
lst[2:5]=10,11,12 #update2ndelementto4thelementinthelist print
lst # [4,7,10,11,12,3]
Deletinganelement fromthe list canbedoneusing ‘del’[Link] takes
the position number of the element to be deleted.
Example:
lst=[5,7,1,8,9,6]
del lst[3] #delete3rdelementfromthelist i.e.,8
print lst # [5,7,1,9,6]
Ifwewant todeleteentire list, wecangivestatementlikedel lst.
ConcatenationofTwolists:
Wecansimplyuse„+‟[Link],„x‟and„y‟are
[Link]+y,thelist„y‟isjoinedattheendofthelist„x‟.
Example:
x=[10,20,32,15,16]
y=[45,18,78,14,86]
printx+y #[10,20,32,15,16,45,18,78,14,86]
RepetitionofLists:
Wecanrepeattheelementsofa list „n‟numberoftimesusing„*‟ operator.
x=[10,54,87,96,45]
printx*2 #[10,54,87,96,45,10,54,87,96,45]
MembershipinLists:
Wecancheck ifanelement isamemberofa list byusing„in‟and„notin‟operator. If
theelement isa member ofthe list,then „in‟operatorreturns True otherwisereturns False. If
theelement is not inthe list, then„not in‟operator returns Trueotherwisereturns False.
Example:
x=[10,20,30,45,55,65]
a=20
print a in x #True
a=25
print a in x #False
a=45
printanotinx#False a=40
printanotinx#True
Aliasingand Cloning Lists:
Givinganew nametoanexistinglistiscalled‘aliasing’.Thenew nameiscalled
‘aliasname’.Toprovideanewnametothis list,wecansimplyuseassignmentoperator(=).
Example:
x=[10,20,30,40,50,60]
y=x #xisaliasedasy
printx #[10,20,30,40,50,60]
printy #[10,20,30,40,50,60]
x[1]=90 #modify1stelement inx
print x # [10,90,30,40,50,60]
printy #[10,90,30,40,50,60]
In this case we are having onlyone list of elements but with two different names „x‟
and „y‟. Here, „x‟ is the originalname and „y‟ is the alias name forthe same list. Hence, any
modificationsdonetox‟willalso modify„y‟ and viceversa.
Obtainingexact copyof anexistingobject (or list) iscalled „cloning‟.To Clonea list, we
can take help of the slicing operation [:].
Example:
x=[10,20,30,40,50,60]
y=x[:] #xiscloned asy
printx #[10,20,30,40,50,60]
printy #[10,20,30,40,50,60]
x[1]=90 #modify1stelement inx
print x # [10,90,30,40,50,60]
printy #[10,20,30,40,50,60]
When we clone a list like this, a separate copy of all the elements is stored into „y‟.
Thelists„x‟and„y‟[Link],anymodificationsto„x‟willnotaffect„y‟and vice
versa.
MethodsinLists:
Method Description
[Link](x) Returnsthefirst occurrenceofx inthelist.
[Link](x) Appendsxatthe endofthe list.
[Link](i,x) Insertsxtothelistinthepositionspecifiedbyi.
[Link]() Copiesallthelistelementsinto anewlistandreturns it.
[Link](lst2) Appendslst2to list.
[Link](x) Returnsnumberofoccurrencesofx inthelist.
[Link](x) Removesx fromthelist.
[Link]() Removestheendingelementfromthelist.
[Link]() Sortstheelementsoflistintoascendingorder.
[Link]() Reversesthe sequenceofelementsinthe list.
[Link]() Deletesallelements fromthelist.
max(lst) Returnsbiggestelementinthelist.
min(lst) Returnssmallestelementinthe list.
Example:
lst=[10,25,45,51,45,51,21,65]
[Link](1,46)
printlst #[10,46,25,45,51,45,51,21,65]
[Link](45) #2
FindingCommonElementsin Lists:
Sometimes, it is useful to know which elements are repeated in [Link] example,
there is a scholarship for which a group of students enrolled in a college. There is another
scholarship for which another group of students got enrolled. Now, we wan to know the
names of the students who enrolled for both the scholarships so that we can restrict them to
take only one scholarship. That means, we are supposed to find out the common students (or
elements) both the lists.
First of all, we should convert the lists into lists into sets, using set( ) function, as:
set(list). Then we should find the common elements in the two sets using intersection()
method.
Example:
scholar1=[„mothi‟,„sudheer‟,„vinay‟,„narendra‟,„ramakoteswararao‟
]scholar2=[„vinay‟,„narendra‟,„ramesh‟]
s1=set(scholar1)
s2=set(scholar2)
s3=[Link](s2)
common =list(s3)
printcommon #display[„vinay‟,„narendra‟]
NestedLists:
A list within another list is called a nested list. We know that a list contains several
elements. Whenwetakealist asanelement inanotherlist,thenthat list iscalledanestedlist.
Example:
a=[10,20,30]
b=[45,65,a]
print b #display[45,65,[10,20,30]] print
b[1] # display 65
print b[2] #display[10,20,30]
print b[2][0] # display 10
print b[2][1] # display 20
print b[2][2] # display 30
for x in b[2]:
printx, # display10 2030
NestedListsasMatrices:
Supposewewantto createamatrixwith3rows3columns, weshouldcreatealist with 3
other lists as:
mat=[[1,2,3],[4,5,6],[7,8,9]]
Here,„mat‟ isa list that contains3 listswhicharerowsofthe„mat‟[Link] again 3
elements as:
[[1, 2,3], #firstrow
[4,5, 6], #second row
[7,8, 9]] #thirdrow
Example:
mat=[[1,2,3],[4,5,6],[7,8,9]]
forrinmat:
print r
print""
m=len(mat)
n=len(mat[0])
for i in range(0,m):
forjinrange(0,n):
printmat[i][j],
print ""
print""
One of the main use of nested lists is that they can be used to represent matrices. A
matrix represents a group of elements arranged in several rows and columns. In python,
matrices are created as 2D arrays or using matrix object in numpy. We can also create a
matrix using nested lists.
Q)Writea programtoperformadditionoftwomatrices.
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[4,5,6],[7,8,9],[1,2,3]]
c=[[0,0,0],[0,0,0],[0,0,0]]
m1=len(a)
n1=len(a[0])
m2=len(b)
n2=len(b[0])
for i in range(0,m1):
forjinrange(0,n1):
c[i][j]=a[i][j]+b[i][j]
for iinrange(0,m1):
forjinrange(0,n1): print
"\t",c[i][j],
print""
Q)Writeaprogramto performmultiplicationoftwomatrices.
a=[[1,2,3],[4,5,6]]
b=[[4,5],[7,8],[1,2]]
c=[[0,0],[0,0]]
m1=len(a)
n1=len(a[0])
m2=len(b)
n2=len(b[0])
for i in range(0,m1):
forjinrange(0,n2):
forkinrange(0,n1):
c[i][j]+=a[i][k]*b[k][j]
for i in range(0,m1):
forjinrange(0,n2):
print"\t",c[i][j],
print ""
ListComprehensions:
List comprehensions represent creationofnew lists froman iterable object (like a list,
set, tuple, dictionary or range) that satisfy a given condition. List comprehensionscontain
verycompact code usually a single statement that performs the task.
Wewantto create alistwithsquaresofintegersfrom1to [Link] codeas:
squares=[]
for iinrange(1,11):
[Link](i**2)
Theprecedingcodewillcreate„squares‟listwiththeelementsasshownbelow:
[1,4,9,16,25,36,49,64,81,100]
Thepreviouscodecanrewritten inacompactwayas:
squares=[x**2for xinrange(1,11)]
This is called list comprehension. From this, we can understand that a list
comprehension consists of square braces containing an expression (i.e., x**2). After the
expression, a fro loop and then zero or more if statements can be written.
[expression for item1 in iterable if statement1
for item1 in iterable if statement2
for item1 in iterable if statement3…..]
Example:
Even_squares = [ x**2 for x in range(1,11) if x%2==0 ]
It will display the list even squares as list.
[4,16,36,64,100]
TUPLE:
A Tuple is a python sequence which stores a group of elements or items. Tuples are
similar to lists but themain difference is tuples are immutable whereas lists are mutable. Once
we create a tuple we cannot modify its elements. Hence, we cannot performoperations like
append(), extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally used
to store data which should not be modified and retrieve that dataondemand.
CreatingTuples:
Wecancreate atuplebywritingelementsseparatedbycommasinsideparentheses( ).
Theelementscanbesamedatatypeordifferenttypes.
Tocreateanemptytuple,wecansimplywriteemptyparenthesis,as:
tup=()
To create a tuple with only one element, we can, mention that element in parenthesis
and after that a comma is needed. In the absence of comma, python treats the element assign
ordinary data type.
tup=(10) tup =(10,)
printtup #display10 printtup #display10
printtype(tup) #display<type „int‟> printtype(tup) #display<type„tuple‟>
To createatuple withdifferenttypes ofelements:
tup=(10,20, 31.5,„Gudivada‟)
Ifwedo notmentionanybracketsandwritetheelementsseparatingthembycomma, then
they are taken by default as a tuple.
tup=10,20,34,47
It is possible to create atuple froma list. This is done byconverting a list into atuple
using tuple function.
n=[1,2,3,4]
tp=tuple(n)
printtp #display(1,2,3,4)
Another waytocreateatuplebyusingrange()functionthatreturnsa sequence.
t=tuple(range(2,11,2))
printt #display(2,4,6,8,10)
Accessingthetuple elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is
same asthatofa list. Indexingrepresentsthepositionnumber oftheelement inthetuple. The
position starts from 0.
tup=(50,60,70,80,90)
printtup[0] #display50
printtup[1:4] #display(60,70,80)
printtup[-1] #display90
print tup[-1:-4:-1] #display(90,80,70)
printtup[-4:-1] #display(60,70,80)
Updatinganddeletingelements:
Tuplesare immutablewhichmeansyoucannot update,changeordeletethevaluesof tuple
elements.
Example-1:
Example-2:
However,youcanalwaysdeletetheentiretuplebyusingthestatement.
Notethat thisexception israised becauseyou aretryingprint thedeletedelement.
Operationson tuple:
Operation Description
len(t) Returnthelengthoftuple.
tup1+tup2 Concatenationoftwotuples.
Tup*n Repetitionoftuplevaluesin nnumber oftimes.
xin tup ReturnTrueifxisfoundintupleotherwisereturnsFalse.
cmp(tup1,tup2) Compareelementsofbothtuples
max(tup) Returnsthemaximumvalueintuple.
min(tup) Returnstheminimumvalueintuple.
tuple(list) Convertlistintotuple.
Returnshowmanytimestheelement„x‟isfoundin tuple.
[Link](x)
Returnsthefirstoccurrenceoftheelement„x‟intuple.
[Link](x)
Raises ValueErrorif„x‟ is not found inthe tuple.
Sorts the elements of tuple into ascending order.
sorted(tup)
sorted(tup,reverse=True)willsortinreverseorder.
cmp(tuple1,tuple2)
Themethod cmp()compareselementsoftwotuples.
Syntax
cmp(tuple1,tuple2)
Parameters
tuple1--This isthefirsttupletobecompared
tuple2--This isthesecondtupletobecompared
ReturnValue
Ifelementsareofthesametype, performthecompareand [Link] different
types, check to see if they are numbers.
Ifnumbers,performnumericcoercion ifnecessaryandcompare.
Ifeitherelement isanumber,thentheotherelement is"larger" (numbersare
"smallest").
Otherwise, typesaresortedalphabeticallybyname.
Ifwereachedtheendofoneofthetuples, thelongertuple is"larger."Ifweexhaust both tuples and
share the same data, the result is a tie, meaning that 0 is returned.
Example:
tuple1 = (123, 'xyz')
tuple2 = (456, 'abc')
print cmp(tuple1, tuple2) #display-1
printcmp(tuple2,tuple1) #display1
NestedTuples:
Pythonallowsyoutodefineatupleinsideanothertuple. Thisiscalledanestedtuple.
students=((“RAVI”,“CSE”,92.00),(“RAMU”,“ECE”,93.00),(“RAJA”,“EEE”,87.00))
for iinstudents:
printi
Output:(“RAVI”,“CSE”,92.00)
(“RAMU”,“ECE”,93.00)
(“RAJA”,“EEE”,87.00)
SET:
Setisanotherdatastructuresupported [Link], setsaresameaslistsbut
with a difference that sets are lists with no duplicate [Link] a set is a mutable and
an unordered collection of items. This means that we can easily add or remove itemsfrom it.
Creatinga Set:
Aset iscreatedbyplacingalltheelements insidecurlybrackets{}. Separatedby comma or
by using the built-in function set( ).
Syntax:
Set_variable_name={var1, var2,var3,var4,…….}
Example:
s={1,2.5,“abc”}
prints #displayset([1,2.5,“abc” ])
Converting alistinto set:
Asetcanhaveanynumber [Link]()
functionisusedtoconvertinglistintoset.
s=set( [1,2.5,“abc”] )
print s #displayset([1,2.5,“abc”]) We
can also convert tuple or string into set.
tup=( 1, 2, 3, 4, 5)
print set(tup)#set([1,2,3,4,5]) str=
“MOTHILAL”
printstr #set(['i','h', 'm','t', 'o'])
Operationsonset:
Sno Operation Result
1 len(s) numberofelementsinsets(cardinality)
2 xins test xformembershipins
3 xnotins testxfornon-membershipins
[Link](t)
4 (or) testwhether everyelementinsisint
s<=t
[Link](t)
5 (or) testwhether everyelementintisins
s>=t
ReturnsTrueiftwosetsareequivalent andreturns
6 s==t
False.
ReturnsTrueiftwosetsarenotequivalent and returns
7 s!=t
False.
[Link](t)
8 (or) newsetwithelementsfrombothsand t
s|t
[Link](t)
9 (or) newsetwithelementscommontosandt
s&t
Sno Operation Result
[Link](t)
10 (or) newsetwithelementsinsbutnotint
s-t
s.symmetric_difference(t)
11 (or) newsetwithelementsineither sortbutnot both
s^t
12 [Link]() new setwithashallow copyofs
13 [Link](t) returnsetswithelementsaddedfromt
14 s.intersection_update(t) returnsetskeepingonlyelementsalsofoundint
15 s.difference_update(t) returnsetsafterremovingelementsfoundint
s.symmetric_difference_up
16 returnset swithelementsfromsortbut notboth
date(t)
17 [Link](x) addelementxtoset s
18 [Link](x) removexfromsets;raisesKeyErrorifnotpresent
19 [Link](x) removesxfromsetsifpresent
removeandreturnanarbitraryelement froms; raises
20 [Link]()
KeyError if empty
21 [Link]() removeallelementsfromsets
22 max(s) ReturnsMaximumvalueinaset
23 min(s) ReturnsMinimumvalueina set
Returnanewsortedlist fromtheelementsinthe set.
24 sorted(s)
Note:
Tocreateanemptysetyoucannotwrites={}, becausepythonwillmakethisasa
directory. Therefore,tocreateanemptysetuseset()function.
s=set() s={}
printtype(s) #display<type„set‟> printtype(s)#display<type„dict‟>
Updatingaset:
Sincesetsareunordered,[Link] to
access or change an element using indexing or slicing.
Dictionary:
A dictionaryrepresents a group of elements arranged in the form of key-value pairs.
Thefirstelementisconsideredas„key‟andtheimmediatenextelementistakenasits
„value‟. The keyand its value are separated bya colon (:). Allthe key-value pairs in a
dictionary are inserted in curly braces { }.
d={„[Link]‟:556,„Name‟:‟Mothi‟, „Branch‟:„CSE‟}
Here,thenameofdictionaryis„dict‟.Thefirstelementinthedictionaryisa string
„[Link]‟.So,thisiscalled„key‟. Thesecondelementis556whichistakenasits„value‟.
Example:
d={„[Link]‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟ } print
d[„[Link]‟] # 556
printd[„Name‟] #Mothi
printd[„Branch‟] # CSE
To access the elements ofa dictionary, we should not use indexing or slicing. For example,
dict[0]ordict[1:3][Link] accessthevalueassociatedwithakey, we can
mention the key name inside the square braces, as: dict[„Name‟].
Ifwewantto knowhowmanykey-valuepairsarethereinadictionary, we canusethe len( ) function, as
shown
d={„[Link]‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟}print
len(d) #3
Wecanalso insert anewkey-valuepair into [Link] mentioning the
key and assigning a value to it.
d={'[Link]':556,'Name':'Mothi','Branch':'CSE'}
print d #{'Branch':'CSE','Name':'Mothi','[Link]':556}
d['Gender']="Male"
print d #{'Gender':'Male','Branch': 'CSE','Name':'Mothi','[Link]':556}
Suppose,wewantto deleteakey-valuepairfromthedictionary,wecanusedelstatementas:
deldict[„[Link]‟]#{'Gender':'Male','Branch':'CSE','Name':'Mothi'}
ToTestwhethera„key‟isavailableinadictionary ornot,wecanuse„in‟and„noti‟n operators.
These operators return either True or False.
„Name‟ind #checkif„Name‟isakeyindandreturnsTrue/False
[Link],avaluecanbeanumber,string, list,tuple or another
dictionary. But keys should obey the rules:
Keys should be unique. It means, duplicate keys are not allowd. Ifwe enter same key
again, the old keywill be overwritten and only the new key will beavailable.
emp={'nag':10,'vishnu':20,'nag':20}
printemp#{'nag':20, 'vishnu':20}
Keys should be immutable type. For example, we can use a number, string ortuplesas
keys since they are immutable. We cannot use lists or dictionaries as keys. If they are
used as keys, we will get „TypeError‟.
emp={['nag']:10,'vishnu':20,'nag':20}
Traceback (most recent call last):
File"<pyshell#2>",line1,in<module>em
p={['nag']:10,'vishnu':20,'nag':20}
TypeError:unhashabletype:'list'
Dictionary Methods:
Method Description
[Link]() Removesallkey-valuepairsfromdictionary„d‟.
d2=[Link]() Copiesallelementsfrom„d‟intoanewdictionaryd2.
Createanewdictionarywithkeysfromsequence„s‟and values
[Link](s[,v]) all set to „v‟.
Returnsthevalueassociatedwithkey„k‟. Ifkeyisnot found, it
[Link](k[,v]) returns „v‟.
Returnsanobjectthat containskey-valuepairsof„d‟.The pairs
[Link]() are stored as tuples in the object.
[Link]() Returnsasequenceofkeysfromthedictionary„d‟.
[Link]() Returnsasequenceofvaluesfromthedictionary„d‟.
[Link](x) Addsallelementsfromdictionary„x‟to„d‟.
Removesthekey„k‟anditsvaluefrom„d‟andreturnsthe value.
Ifkeyis notfound,thenthevalue„v‟isreturned. If
[Link](k[,v])
keyisnotfoundand„v‟isnotmentionedthen„KeyError‟ is
raised.
If key„k‟ is found, its valueis returned. Ifkeyis not
[Link](k[,v])
found,thenthek,vpairisstoredintothedictionary„d‟.
Using forloop withDictionaries:
forloopisveryconvenienttoretrievetheelementsofadictionary. Let‟stakeasimple
dictionary that contains color code and its name as:
colors={'r':"RED",'g':"GREEN", 'b':"BLUE",'w':"WHITE"}
Here, „r‟, „g‟, „b‟ represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟
indicate values.
colors={'r':"RED",'g':"GREEN", 'b':"BLUE",'w':"WHITE"}
forkincolors:
printk#displaysonlykeys for
k in colors:
printcolors[k] #keystotodictionaryanddisplaythe values
Converting Listsinto Dictionary:
Whenwe have two lists, it is possible to convert them into a dictionary. For example,
we have two lists containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to
create a „zip‟ class object by passing the two lists to zip( ) function. The zip( ) function is
useful to convert the sequences into a zip class object. The second step is to convert the zip
object into a dictionary by using dict( ) function.
Example:
countries=['USA', 'INDIA','GERMANY','FRANCE' ]
cities=['Washington','NewDelhi','Berlin','Paris']
z=zip(countries, cities)
d=dict(z)
print d
Output:
{'GERMANY':'Berlin','INDIA':'NewDelhi','USA':'Washington','FRANCE':'Paris'}
PYTHONPROGRAMMING UNIT-3
Converting StringsintoDictionary:
Whenastring isgivenwithkeyandvaluepairsseparatedbysomedelimiter likea comma ( ,
) we can convert the string into a dictionaryand use it as dictionary.
s="Vijay=23,Ganesh=20,Lakshmi=19,Nikhil=22"
s1=[Link](',')
s2=[]
d={}
for i in s1:
[Link]([Link]('='))
printd
{'Ganesh':'20','Lakshmi':'19','Nikhil':'22','Vijay':'23'}
Q)APythonprogramto create adictionary andfindthe sumofvalues.
d={'m1':85,'m3':84,'eng':86,'c':91}
sum=0
for [Link]():
sum+=i
printsum # 346
Q)APythonprogramto createadictionarywithcricketplayer’snamesandscoresina match.
Also we are retrieving runs by entering the player’s name.
n=input("EnterHowmanyplayers?") d={}
for i in range(0,n):
k=input("EnterPlayername:")
v=input("Enter score: ")d[k]=v
printd
name=input("Enternameofplayerforscore:") print
"The Score is",d[name]
Enter How many players? 3
EnterPlayername:"Sachin"
Enter score: 98
EnterPlayername:"Sehwag"
Enter score: 91
EnterPlayername:"Dhoni" Enter
score: 95
{'Sehwag': 91, 'Sachin': 98, 'Dhoni': 95}
Enternameofplayerforscore:"Sehwag" The
Score is 91