Hacking Secret Ciphers with Python

(Ann) #1

172 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


brackets with the key in between them (just like indexing with lists). Try typing the following
into the interactive shell:





spam = {'key1':'This is a value', 'key2':42}
spam['key1']
'This is a value'
spam['key2']
42





It is important to know that, just as with lists, variables do not store dictionary values themselves,
but references to dictionaries. The example code below has two variables with references to the
same dictionary:





spam = {'hello': 42}
eggs = spam
eggs['hello'] = 99
eggs
{'hello': 99}
spam
{'hello': 99}





Adding or Changing Items in a Dictionary


You can add or change values in a dictionary with indexes as well. Try typing the following into
the interactive shell:





spam = {42:'hello'}
print(spam[42])
hello
spam[42] = 'goodbye'
print(spam[42])
goodbye





And just like lists can contain other lists, dictionaries can also contain other dictionaries (or lists).
Try typing the following into the interactive shell:





foo = {'fizz': {'name': 'Al', 'age': 144}, 'moo':['a', 'brown', 'cow']}
foo['fizz']
{'age': 144, 'name': 'Al'}
foo['fizz']['name']




Free download pdf