Hacking Secret Ciphers with Python

(Ann) #1
Chapter 20 – Frequency Analysis 315

Sorting the Items from a Dictionary


freqAnalysis.py
51. # fourth, convert the freqToLetter dictionary to a list of tuple
52. # pairs (key, value), then sort them
53. freqPairs = list(freqToLetter.items())


The fourth step of getFrequencyOrder() is to sort the strings from the freqToLetter
dictionary by the frequency count. Remember that the freqToLetter dictionary has integer
frequency counts for the keys and lists of single-letter strings for the values. But since dictionaries
do not have an ordering for the key-value pairs in them, we will call the items() method and
list() function to create a list of tuples of the dictionary’s key-value pairs. This list of tuples
(stored in a variable named freqPairs on line 5 3 ) is what we will sort.


freqAnalysis.py
54. freqPairs.sort(key=getItemAtIndexZero, reverse=True)


The sort() method call is passed the getItemAtIndexZero function value itself. This
means the items in the freqPairs will be sorted by the numeric order of the value at index 0 of
the tuple value, which is the frequency count integer. Line 5 4 also passes True for the reverse
keyword argument so that the tuples are reverse ordered from largest frequency count to smallest.


If we continue using the previous “Alan Mathison Turing...” example, the value of freqPairs
will be [(196, 'E'), (140, 'T'), (139, 'I'), (135, 'A'), (122, 'N'), (113,
'O'), (106, 'R'), (89, 'S'), (87, 'H'), (74, 'C'), (62, 'L'), (58,
'MD'), (39, 'G'), (37, 'FU'), (36, 'P'), (30, 'BW'), (21, 'Y'), (14,
'V'), (8, 'K'), (3, 'X'), (2, 'QJ'), (1, 'Z')]


freqAnalysis.py
56. # fifth, now that the letters are ordered by frequency, extract all
57. # the letters for the final string
58. freqOrder = []
59. for freqPair in freqPairs:
60. freqOrder.append(freqPair[1])


The fifth step is to create a list of all the strings from the sorted list in freqPairs. The variable
freqOrder will start as a blank list on line 58, and the string at index 1 of the tuple in
freqPairs will be appended to the end of freqOrder.


If we continue with the “Alan Mathison Turing was a British mathematician...” example from
before, after this loop has finished, freqOrder will contain the value ['E', 'T', 'I',

Free download pdf