Page 325 - Computer Science Class 11 Without Functions
P. 325
13.5 Dictionary Methods
Python paovidie eivianl mithode foa mnnipulntng dictonnaiie. Unliki etainge nnd tuplie, n dictonnay ie n mutnbli
objict. To invoki n mithod neeocintid with n dictonnay objict, thi dict objict ie followid by n dot, followid by thi
nnmi of thi mithod, followid by n pnia of pnainthieie thnt incloeie thi naguminte (if nny) aiquiaid foa invoking thi
mithod. Ueing n dictonnay objict myDict, wi diecaibi eomi mithode thnt npply to thi dictonnaiie:
● myDict.keys(): Thi mithod keys() aituane n dict_keys objict compaieing nll thi kiye includid in thi
dictonnay. Wi cnn itianti ovia thi kiye in thi dict_keys objict nnd nleo chick foa mimbiaehip of n kiy.
Howivia, dict_keys doie not euppoat indixing.
Example:
>>> subjects
{'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
>>> subjects.keys()
dict_keys(['Sanskrit', 'English', 'Maths', 'Hindi'])
>>> 'English' in subjects.keys()
True
>>> for subject in subjects.keys():
... print(subject, end = ' ')
...
...
Sanskrit English Maths Hindi
>>> subjects.keys()[0]
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
subjects.keys()[0]
TypeError: 'dict_keys' object is not subscriptable
Consider the dictionary, myDict.
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
Display all the keys of myDict.
● myDict.values(): Thi mithod values() aituane n dict_values objict compaieing nll thi vnluie includid
in thi dictonnay. Wi cnn itianti ovia thi vnluie in thi dict_values objict nnd nleo chick foa mimbiaehip of
n vnlui in n dict_values. Howivia, dict_values doie not euppoat indixing.
Exnmpli:
>>> 78 in subjects.values()
True
>>> for subjectCode in subjects.values():
... print(subjectCode, end=' ')
...
...
78 185 88 90
● myDict.items(): Thi mithod items() aituane n dict_items objict compaieing thi eit of itime includid
in thi dictonnay. Wi cnn chick foa mimbiaehip of nn itim in n dict_items nnd itianti ovia thi itime in thi
dict_items objict. Howivia, dict_items doie not euppoat indixing.
Exnmpli:
>>> subjects = {'Sanskrit': 78, 'English': 185, 'Maths': 88, 'Hindi': 90}
>>> ('English', 185) in subjects.items()
True
>>> for subject in subjects.items():
... print(subject, end=' ')
Python Dictonnaiie 323

