Dictionaries
Next to lists, dictionaries are one of the most useful data types in Python. Python dictionaries are unordered collections of objects, matched to a keyword. Python lists, on the other hand, are ordered collections that use a numerical offset.
Because of their construction, dictionaries can replace many "typical" search algorithms and data structures found in C and related languages. For those coming from other languages, Python dictionaries are just like a hash table, where an object is mapped to a key name.
Dictionaries include the following properties:
Here's the (now standard) list of common operations:
Making a dictionary
As previously stated, you create dictionaries and access items via a key. The key can be of any immutable type, like a string, number, or tuple. The values can be any type of object, including other dictionaries. The format for making a dictionary is like so:
>>>dictionary = {“key name”: “value}
However, the key name and value can be anything allowed, such as:
>>>dictionary = {“cow”: “barn”, 1: “pig”, 2: [“spam”, “green”, “corn”]}
Notice that the brackets for dictionaries are curly braces, the separator between a key word and it’s associated value is a colon, and that each key/value is separated by a comma. This are just some of the things that can cause syntax errors in your program.
Basic operations
The len() function can be used to give the number of items stored in a dictionary or the length of the key list. The keys() method returns all the keys in the dictionary as a list. Here's a few examples:
Generic Code Example:
>>> d2 = {'spam' : 2, 'ham': 1, 'eggs' : 3}
>>> d2['spam'] # fetch value for key
2
>>> len(d2) # number of entries in dictionary
3
>>> d2.has_key('ham') # does the key exist? (1 means true)
1
>>> d2.keys() # list of my keys
['eggs', 'spam', 'ham']
Since dictionaries are mutable, you can add and delete values to them without creating a new dictionary object. Just assign a value to a key to change or create an entry and use del to delete an object associated with a given key.
Generic Code Example:
>>> d2['ham'] = ['grill', 'bake', 'fry'] # change entry
>>> d2
{'eggs' : 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']}
>>> del d2['eggs'] # delete entry
>>> d2
{'spam': 2, 'ham': ['grill', 'bake', 'fry']}
>>> d2['brunch'] = 'Bacon' # add new entry
>>> d2
{'brunch': 'Bacon', 'ham': ['grill', 'bake', 'fry'], 'spam': 2}
To compare with lists, adding a new object to a dictionary only requires making a new keyword and value. Lists will return an "index out-of-bounds" error if the offset is past the end of the list. Therefore you must use append or slicing to add values to lists.
Here is a more realistic dictionary example. The following example creates a table that maps programming language names (the keys) to their creators (the values). You fetch a creator name by indexing on language name:
Generic Code Example:
>>> table = {'Python' : 'Guido van Rossum',
... 'Perl': 'Larry Wall',
... 'Tcl': 'John Ousterhout' }
...
>>> language = 'Python'
>>> creator = table[language]
>>> creator
'Guido van Rossum'
>>> for lang in table.keys(): print lang, '\t', table[lang]
...
Tcl John Ousterhout
Python Guido van Rossum
Perl Larry Wall
From this example, you might notice that the last command is similar to string and list iteration using the for command. However, you'll also notice that, since dictionaries aren't sequences, you can't use the standard for statement. You must use the keys() method to return a list of all the keywords which you can then iterate through like a normal list.
You may have also noticed that dictionaries can act like light-weight databases. The example above creates a table, where the programming language “column” is matched by the creator’s “row”. If you have a need for a database, you might want to consider using a dictionary instead. If the data will fit, you will save yourself a lot of unnecessary coding and reduce the headaches you would get from dealing with a database.
Dictionary details
As previously stated, dictionaries are mappings, not sequences. Because there's no order to dictionary items, functions like concatenation and slicing don't work.
Keys can be created when making a dictionary constant (i.e. when you initially create the dictionary) or by adding new values to an existing dictionary. The process is similar and the end result is the same.
The previous examples showed keys as string objects, but any non-mutable object (like lists) can be used for a keyword. Numbers can be used to create a list-like object but without the ordering. Tuples (covered later) are sometimes used to make compound keys; class instances designed not to change can also be used if needed.
Well, we're nearly done with Python types. The next chapter will cover tuples, which are basically immutable lists.
Methods
Like the other chapters, a list of common dictionary methods can be found in the appendix.