Additional Operations with Sequences
6.8 Operations with Dictionaries
The Python Interpreter sequence in Fig.6.16 illustrates the use of different func-tions and methods with dictionarys. An empty dictionarydc is formed in [1].dc[‘z0’] = ‘ZZ0’ in [2] enters (‘z0’, ‘ZZ0’) as a (key, value) pair into dc.
Similarly (‘y1’, ‘YY1’) is also added to dc in [3] as can be seen from [4]. With any dictionarya (key, value) pair can be added in this manner. In fact the value associated with an existing (key:value) pair can also be changed with a similar fresh assignment. The dictionary dd in [5] has (‘b1’:‘BB1’) as a (key:
value) pair in it. The value is redefined as ‘bb1’ in [6]. The altered dd is in [7].
If‘z0’ in dc in [8] checks whether ‘z0’ is a key in dc; it being true, ‘yes’ is printed out as desired. Since‘yy’ is not a key in dc [9], a ‘no’ is output. dd[‘a0’]
in [10] checks for the presence of ‘a0’ as a key in dd. If present its value (=‘AA0’) is returned. Since ‘aa’ is not a key in dd, dd[‘aa’] in [11] returns a
‘KeyError’.
For the dictionary dd the method dd.get(‘c2’) in [12] searches for the key‘c2’ in dd. It being present the associated value ‘CC2’ is returned. If the key is absent as withdd.get(aa) in [13] the command is ignored. The same is true of the empty dictionaryddc in [15]: ddc.get(‘aa’) in [16] is ignored. In this respectdd.get() is different from dd[]. [14] is the use of the general form of the get() method. dd.get(‘aa’, bb) checks for key ‘aa’ in dd. If present the cor-responding value is returned. If not the second argument specified—bb—is returned. In the previous case the second argument was left out; since‘aa’ is not a keyindc, the command was ignored.
>>> from demo_5 import marks1
>>> mks = marks1.ss [1]
>>> sm = set(iter(jl[0] for jl in mks)) [2]
>>> sm [3]
{'Sanjay', 'Siva', 'Nisha', 'Kishore', 'Asha'}
>>> fls, pss = set(), set() [4]
>>> for jj in mks:
... if all(jk>=60 for jk in jj[1:]):pss.add(jj[0]) [5]
... if any(jk<60 for jk in jj[1:]):fls.add(jj[0]) [6]
...
>>> fls, pss [7]
({'Siva', 'Nisha'}, {'Sanjay', 'Kishore', 'Asha'})
>>> fls1 = sm - pss [8]
>>> fls1 [9]
{'Siva', 'Nisha'}
>>>
Fig. 6.15 Python Interpreter sequence for Example6.1
124 6 Additional Operations with Sequences
Any dictionary can be updated by adding the (key, value) pairs of another to it. [17] is a simple illustrative example. {‘f5’: ‘FF5’} as a dictionary is added todd. The enhanced dd is in [18].
Example 6.2 Rearrange the marks inss in marks1.py in the form of a dictionary with the students’ names as the keys and the mark-sets as tuples.
The marks frommarks1.py is assigned to a1 [19]. An empty dictionary—
d1—is created in [20] (initialization). Through [21] the desired dictionary is formed. For any integerjj, a1[jj] is the full entry in a1 for the student concerned—
a1[jj][0] is the name and the slice a1[jj][1:] the full set of marks. {a1[jj][0]:a1[jj]
[1:]} is the dictionary for the specific student. d1.update( ) adds it to d1.
This is done for every item ina1 to form the full d1 as in [22].
dd from Fig.6.16is reproduced in the Python Interpreter sequence in Fig.6.17 [1]. The total number of entries in the dictionarydd can be obtained using the len() function as in [2]. The methods keys() and values() can be used directly with a dictionary to sift out the keys and values respectively as done with [3]
and [4]. These values been assigned to kk and vv respectively. They can be converted to lists, sorted lists, tuples, or tuples (sorted()) as desired. If necessary the reverse option can be invoked when sorting. All these are illustrated in the lines following in the sequence.
With items(), dd.items() returns the dictionary items as a set of tuples—with each tuple item being a (key, value) tuple. These can be seen from [19] and [20]. If necessary this set can be converted into a tuple—[21]
& [22] or a list. A (key, value) pair can be deleted from a dictionary using del. deldd[‘d3’] in [23] deletes (‘d3’:‘DD3’) from the dictionary dd as can be seen from [24]. The method dict.fromkeys(‘x’, y) can be used to form a dictionary from the elements of a given sequencex (list or tuple).
Every item in the dictionary so formed is assignedy as its value. de in [25]
is an example wherede is formed as a dictionary with the elements of kkl as the keys. Every entry inde is assigned the value 22 as in [26].
Example 6.3 A stringlo is given. Get the frequencies of all the letters in lo.
dd.get(x, y) is a method which returns the value for the key ‘x’ in the dic-tionarydd. If ‘x’ is not a key in dd y is returned in its place. lfq is initialized as a blank dictionary in [1] in the Python Interpreter sequence in Fig.6.18. For anyjj, lfq[jj] = z assigns the value of z for the key jj. If jj is already present as a key the existing value is discarded. Ifjj is not present in lfq, (jj:z) pair is added to lfq. In [2]
lfq[jj] = lfq.get(jj,0) does the following:
• If jj as a key is absent in lfq, (jj:1) becomes a new entry in lfq.
• If jj is present as a key in lfq, its value as an updated integer is incremented by one—that is the count of jj is increased by one.
In [2] this is done for every character (including white spaces) in the stringlo. Once execution is completelfq has the frequencies of all the characters in the string lo.
dictionarydd from Fig.6.17is reproduced in the Python Interpreter sequence of Fig.6.19in [1]. From the sequence of keys of a dictionary—dd.keys()—one can
>>> dc = {} [1]
>>> if 'z0' in dc: print('yes') [8]
... else:print('no') ...
yes>>> if'yy' in dc: print('yes') [9]
... else:print('no') ...
no>>> dd['a0'] [10]
'AA0'
>>> dd['aa'] [11]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'aa'
>>> dd.get('c2') [12]
'CC2'
>>> dd.get('aa') [13]
>>> dd.get('aa','Sorry, no aa here') [14]
'Sorry, no aa here'
>>> from demo_5 import marks1
>>> a1 = marks1.st [19]
>>> d1 = dict() [20]
Fig. 6.16 Python Interpreter sequence illustrating operations with dictionarys
126 6 Additional Operations with Sequences
form an iterator. But iter(dd)—in a more compact form—does the same. [2] uses it to formee as a list of keys [3]. dd.pop(‘e4’) in [4] pops the value (‘EE4’) for the specified key (‘e4’) for the dictionary dd as in [5]. If such a key is absent in the dictionary a‘KeyError’ will be raised. However if the popping is done with dd.pop
>>> dd = {'a0':'AA0', 'b1':'BB1', 'c2':'CC3',
'd3':'DD3','e4':'EE4'} [1]
>>> len(dd) [2]
5
>>> kk = dd.keys() [3]
>>> vv = dd.values() [4]
>>> kk, vv [5]
(dict_keys(['d3','e4','a0','b1','c2']), dict_values(['DD3','EE4','AA0','BB1','CC3']))
>>> kkl = list(kk) [6]
>>> kkl [7]
['d3', 'e4', 'a0', 'b1', 'c2']
>>> vvl = list(vv) [8]
>>> vvl [9]
['DD3', 'EE4', 'AA0', 'BB1', 'CC3']
>>> kkls = sorted(kkl) [10]
>>> kkls [11]
['a0', 'b1', 'c2', 'd3', 'e4']
>>> kkls1 = sorted(dd.keys()) [12]
>>> kkls1 [13]
['a0', 'b1', 'c2', 'd3', 'e4']
>>> ktp = tuple(dd.keys()) [14]
>>> ktp [15]
('d3', 'e4', 'a0', 'b1', 'c2')
>>> kttp = tuple(sorted(dd.keys())) [16]
>>> kttp [17]
('a0', 'b1', 'c2', 'd3', 'e4')
>>> kttpr = tuple(sorted(dd.keys(), reverse = True)) [18]
>>> kttpr
('e4', 'd3', 'c2', 'b1', 'a0')
>>> dd.items() [19]
dict_items([('d3','DD3'),('e4','EE4'),('a0','AA0'),('b1',
'BB1'),('c2','CC3')]) [20]
>>> dtp = tuple(dd.items()) [21]
>>> dtp [22]
>>> de = dict.fromkeys(kkl, 22) [25]
>>> de [26]
{'d3': 22, 'e4': 22, 'b1': 22, 'c2': 22, 'a0': 22}
Fig. 6.17 Python Interpreter sequence illustrating more operations with dictionaries
(‘e4’, z), the second argument (z) will be returned if ‘e4’ is not a key in dd. In the present case, after step [4]dd does not have (‘e4’:‘EE4’) as an item in it. Hence another attempt to pop withdd.pop(‘e4’, ‘sorry’) in [6] returns ‘sorry’ [7]. dd.
popitem() pops a (key, value) pair selected randomly fromdd. With [8] the item (‘a0’: ‘AA0’) is returned. dd.popitem() is done here repeatedly until dd becomes empty as in [9]. Another attempt to pop an item in [10] returns‘KeyError’.
For a dictionaryd the method d.setdefault(‘x’:y) does the following:
• If ‘x’ is present as a key in d, the associated value is returned. The dic-tionaryremains unaffected.dd is refreshed in [11]. dd.setdefault(‘b1’) in [12] returns ‘BB1’ since the corresponding dictionary item is {‘b1’:‘BB1’}. The dictionary remains untainted.
• If ‘x’ is not present as a key in d, the item {‘x’:y} is entered into the dictionary and the value y is returned. dd.setdefault ({‘f5’:‘FF5’}) in [14] adds the item {‘f5’:‘FF5’} into the dictionary as in [15].
• If the value ‘y’ is not specified in the command, that is if the command is d.setdefault(‘x’) and the key ‘x’ is not a valid key, the item (‘x’:None) is entered into the dictionary—that is ‘x’ is entered as a key with None as the associated default value.‘g6’ is not a key in dd as in [16]. Hence {‘g6’:
None} is added as an additional item in the dictionary.
lo = 'interjection is different from interruption'
>>> lfq = {} [1]
>>> for jj in lo: lfq[jj] = lfq.get(jj,0) + 1 [2]
...
>>> for jk in lfq.items(): print(jk) ... ('i', 6)
('m', 1) ('r', 5) ('u', 1) ('f', 3) ('e', 5) ('s', 1) ('c', 1) (' ', 4) ('d', 1) ('p', 1) ('t', 5) ('j', 1) ('o', 3) ('n', 5)
>>>
Fig. 6.18 Python Interpreter sequence for Example6.3
128 6 Additional Operations with Sequences