Hacking Secret Ciphers with Python

(Ann) #1
Chapter 20 – Frequency Analysis 313

someListVariable.sort()


...as being equivalent to this:


def func(x):
return x # sorting based on the value itself
someListVariable.sort(key=func)


So when the sort() method call is passed ETAOIN.find, instead of sorting the strings like
'A', 'B', and 'C' by the alphabetical order the sort() method sorts them by the numeric
order of the integers returned from ETAOIN.find('A'), ETAOIN.find('B'), and
ETAOIN.find('C'): that is, 2 , 19 , and 11 respectively. So the 'A', 'B', and 'C' strings
get sorted as 'A', 'C', and then 'B' (the order they appear in ETAOIN).


Converting Dictionaries to Lists with the keys(), values(), items() Dictionary Methods


If you want to get a list value of all the keys in a dictionary, the keys() method will return a
dict_keys object that can be passed to list() to get a list of all the keys. There is a similar
dictionary method named values() that returns a dict_values object. Try typing the following
into the interactive shell:





spam = {'cats': 10, 'dogs': 3, 'mice': 3}
spam.keys()
dict_keys(['mice', 'cats', 'dogs'])
list(spam.keys())
['mice', 'cats', 'dogs']
list(spam.values())
[3, 10, 3]





Remember, dictionaries do not have any ordering associated with the key-value pairs they
contain. When getting a list of the keys or values, they will be in a random order in the list. If you
want to get the keys and values together, the items() dictionary method returns a dict_items
object that can be passed to list(). The list() function will then return a list of tuples
where the tuples contain a key and value pair of values. Try typing the following into the
interactive shell:





spam = {'cats': 10, 'dogs': 3, 'mice': 3}
list(spam.items())




Free download pdf