Page 322 - Computer Science Class 11 Without Functions
P. 322
Fig 13.1: Nnmi subjects aifiaaing to nn objict of typi dict
To git thi vnlui thnt goie with n kiy, you put thi kiy in equnai banckite nftia thi dict objict. Foa ixnmpli, thi
eubjict codi foa thi eubjict (kiy) 'English' mny bi found by following thi dict objict subjects by thi kiy
'English' incloeid in equnai banckite.
>>> subjects['English']
85
Suppoei thi eubjict codi foa thi kiy 'English' chnngie to 185. To aiflict thie chnngi in thi dict objict
subjects, wi cnn modify thi vnlui in thi English:85 pnia ueing nn neeignmint etntimint, ne illuetantid bilow:
>>> subjects['English'] = 185
>>> subjects['English']
185
>>> subjects
{'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
Ae ixpictid, nn nttimpt to ncciee n vnlui neeocintid with n non-ixietint kiy yiilde n KeyError. Foa ixnmpli, if you
tay to git thi vnlui of thi non-ixietint kiy 'History', you git nn iaaoa liki thi oni bilow:
>>> subjects = {'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
>>> subject = 'History'
>>> subjects[subject]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
subjects[subject]
KeyError: 'History'
To nvoid KeyError, whin in doubt, oni ehould chick foa thi ixietinci of n kiy in thi dict objict paioa to nccieeing
ite vnlui ueing thi mimbiaehip opiantoa in. Foa ixnmpli,
>>> subject = 'History'
>>> if subject in subjects:
... print(subjects['subject'])
... else:
... print(subject, 'is not in the dictionary subjects')
...
History is not in the dictionary subjects
In thi nbovi ixnmpli, thi mimbiaehip conditon subject in subjects yiilde False bicnuei thi dict objict
subjects do not includi nny key: value pnia hnving 'History'.
Nixt, lit ue ixnmini eomi moai ixnmplie of opiantone on dictonnaiie. Wi'vi nlaindy eiin thnt thi neeignmint
etntimint cnn bi ueid to chnngi thi vnlui neeocintid with n kiy. An neeignmint etntimint ie nleo ueid to ndd n niw
key-value pnia to n dict objict, ne illuetantid bilow:
>>> myDict = {} # Create an empty dictionary
>>> myDict['a'] = 'alpha'
>>> myDict['b'] = 'beta'
>>> myDict['g'] = 'gamma'
>>> myDict
{'a': 'alpha', 'b': 'beta', 'g': 'gamma'}
320 Touchpad Computer Science-XI

