Page 328 - Computer Science Class 11 Without Functions
P. 328
Exnmpli:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> myDict.setdefault('a')
'alpha'
>>> myDict.setdefault('a', 'aa')
'alpha'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha'}
>>> myDict.setdefault('d','delta')
'delta'
>>> myDict
{'b': 'beta', 'g': 'gamma', 'a': 'alpha', 'd': 'delta'}
13.6 Sorting Keys/ Values of a Dictionary
Thi mithod sorted() ie ueid to eoat thi dictonnay by thi keys oa by thi values. By difnult, thi mithod
sorted() aituane n liet of kiye in thi dictonnay in necinding oadia of thi kiye.
Exnmpli:
>>> myDict = { 'b':'beta', 'g':'gamma', 'a':'alpha' }
>>> sorted(myDict) # sorted(myDict.keys())
['a', 'b', 'g']
>>> sorted(myDict, reverse = True)
['g', 'b', 'a']
>>> sorted(myDict.values())
['alpha', 'beta', 'gamma']
Lit ue now uei sorted() mithod to paint nll kiy-vnlui pniae with aiepict to kiye.
>>> for key in sorted(myDict.keys()):
... print(key, ':', myDict[key])
a : alpha
b : beta
g : gamma
13.7 Building a Thesaurus
In thie eicton, wi will build n thienuaue. Foa thie puapoei, wi waiti n paoganm (Paoganm 13.1 ) thnt caintie nnd
mnnngie n thienuaue in thi foam of n dictonnay. Moai epicificnlly, thi paoganm ehould do thi following:
n. Bigin with n thesaurus of n fiw woade, euch ne thi following thienuaue:
>>> thesaurus = {'beautiful':('alluring', 'delightful', 'charming', 'pleasing', 'attractive'),\
'lovely':('cute', 'dazzling'), \
'pretty': ('nice-looking', 'beautiful')}
b. Populnti thi thienuaue with thi word: synonyms pniae. Foa inch word, synonyms ie n tupli of ite eynonyme.
Thi paoganm ehould aipintidly paompt thi ueia with n mieengi Want to add more words and synonyms?
(Y/y) nnd contnui to nccipt word: synonyms eo long ne thi ueia aieponde with Y oa y.
c. Whin no moai word: synonyms nai to bi nddid, dieplny thi thesaurus conetauctid in etip b.
d. Ripintidly nek thi ueia, whithia hi/ehi would liki to contnui with thi thienuaue opiantone. So long ne thi ueia
aieponde with Y or y, do thi following:
i. Aek thi ueia to intia n woad (w) whoei eynonyme nai aiquiaid.
ii. Paompt thi ueia to intia w with thi mieengi 'Enter a word:'
iii. Find thi eynonyme of thi woad w (intiaid by thi ueia) in thesaurus.
iv. Thi paoganm ehould yiild nll eynonyme of w.
326 Touchpad Computer Science-XI

