Hacking Secret Ciphers with Python

(Ann) #1

174 http://inventwithpython.com/hacking


Email questions to the author: [email protected]








The not in operator works with dictionary values as well.


Using for Loops with Dictionaries


You can also iterate over the keys in a dictionary with for loops, just like you can iterate over
the items in a list. Try typing the following into the interactive shell:





spam = {'name':'Al', 'age':99}
for k in spam:
... print(k)
... print(spam[k])
... print('==========')





age
99


name
Al








Practice Exercises, Chapter 12, Set C


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


The Difference Between Dictionaries and Lists


Dictionaries are like lists in many ways, but there are a few important differences:



  1. Dictionary items are not in any order. There is no “first” or “last” item in a dictionary like
    there is in a list.

  2. Dictionaries do not have concatenation with the + operator. If you want to add a new
    item, you can just use indexing with a new key. For example, foo['a new key'] =
    'a string'

  3. Lists only have integer index values that range from 0 to the length of the list minus one.
    But dictionaries can have any key. If you have a dictionary stored in a variable spam,
    then you can store a value in spam[3] without needing values for spam[0],
    spam[1], or spam[2] first.

Free download pdf