Wednesday, March 14, 2012

csci133c5.py

In python, there is an extremely useful data type called dictionary. What a dictionary is a collection of unordered (key, value) pairs. Notice, one value can be mapped to one key only, so if you try to add another value with the same key, it will change the value it originally assigned to it. It makes sense because if you have a few values mapped to the same key, you have no idea which is which.

Take a look at the example for the dictionary below
passwords = {'george':'dog', 'gerry':'cat', 'stephen':'chicken'}
name = input('Username: ')
password = input('Password: ')
if name == passwords[password]:
   print('Correct, welcome:', name)
else:
   print('Sorry, bad password.')
Output:
Username: george
Password: dog
Correct, welcome: george

Username: george
Password: cat
Sorry, bad password.
Reference: http://docs.python.org/tutorial/datastructures.html#dictionaries
And lastly, we can not use a list as the key either, because you can modify a list by accessing it with the index assignment, slice assignment or other methods. You create a dictionary with a pair of braces{}, it is now an empty dictionary. You separate the entries by comma, and you give the value to the key by :. key: value is the syntax for the dictionary entries.
  • keys(), which return a list of all the keys used in the dictionary
  • del dictionary[key], delete the key:value pair
  • if you store a key that is already has a value, the old value will be gone
  • the keys can be strings and numbers 
  • the value can be objects of any kind
When you want to look up a key and see what its value is, do this:
passwords['george']
# Return value will be 'dog'
Look at line 4, there is a if statement, similar to C++, if is a control flow statement. You can write a else statement that allow it to be executed when the if statement condition is not satisfy. But you can just use if statement by itself too.
myNum = 10
if myNum > 5:
    print('My number is greater than 5') # Totally cool too
So, now you know for loop, you know how to open a file, and a if else. Let's start to create some program with them. It is like lego, when you have more parts, you can create more complex (powerful) projects.

No comments:

Post a Comment