This post has been migrated from an old server & blog system. Some things may look strange, such as formatting. Some links and images may be broken. I will try getting around to fixing it ASAP.
The dictionary datatype in Python works like a hash table in Perl. It stores pairs of keys and values. It is very efficient at retrieving values when given a particular key. Here are a few examples of ways to use dictionaries in Python:
[python]>>> dict = {} # empty dictionary
>>> dict['a'] = 'hello' # adding new key/value pair: key 'a' value 'hello'
>>> dict['bob'] = 6 # keys can be strings and values can be anything - number, string...
>>> dict['a'] # getting value of a
'hello'
>>> dict['bob']
6
>>> dict[6] = 'frank' # keys can be integers as well
>>> dict.keys() # method to return all keys in dictionary
['a', 'bob', 6]
>>> dict.values() # method to return values
['hello', 6, 'frank']
>>> 'a' in dict # testing if key 'a' is in dict
True
>>> 'x' in dict # testing if key 'x' is in dict
False
>>> print dict # print contents of dictionary
{'a': 'hello', 'bob': 6, 6: 'frank'}
[/python]
I like that it is very easy to just add new key/value pairs to a dictionary. I'm trying to finish an exercise using dictionaries and files in Python, so I will edit this post with my results once I finish it!