Hacking Secret Ciphers with Python

(Ann) #1
Chapter 12 – Detecting English Programmatically 173

'Al'





foo['moo']
['a', 'brown', 'cow']
foo['moo'][1]
'brown'





Practice Exercises, Chapter 12, Set B


Practice exercises can be found at http://invpy.com/hackingpractice12B.


Using the len() Function with Dictionaries


The len() function can tell you how many items are in a list or how many characters are in a
string, but it can also tell you how many items are in a dictionary as well. Try typing the
following into the interactive shell:





spam = {}
len(spam)
0
spam['name'] = 'Al'
spam['pet'] = 'Zophie the cat'
spam['age'] = 89
len(spam)
3





Using the in Operator with Dictionaries


The in operator can also be used to see if a certain key value exists in a dictionary. It is important
to remember that the in operator checks if a key exists in the dictionary, not a value. Try typing
the following into the interactive shell:





eggs = {'foo': 'milk', 'bar': 'bread'}
'foo' in eggs
True
'blah blah blah' in eggs
False
'milk' in eggs
False
'bar' in eggs
True
'bread' in eggs
False




Free download pdf