GIDNetwork > Beginning Python Tutorial (Part 5)
« Things to Avoid in C/C++ -- scanf / epilogue, Part 9 Beginning Python Tutorial (Part 6) »

Beginning Python Tutorial (Part 5)

by: crystalattice - Oct 04, 2005

Python Dictionaries

Next to lists, dictionaries are one of the most useful data types in Python. Python dictionaries are unordered collections of objects, typed to a keyword. Python lists, on the other hand, are ordered collections that use an offset. Because of their construction, dictionaries can replace many "typical" search algorithms and data structures found in C and related languages.

Dictionaries include the following properties:

  • Accessed by keyword, not an offset. Dictionaries are similar to associative arrays.

  • Stored objects are in a random order to provide faster lookup. When created, a dictionary stores items in any order it chooses. To get a value, simply supply the key.

  • They are variable length, can hold objects of any type (including other dictionaries), and support deep nesting.

  • They are mutable but can't be modified like lists or strings; they are the only data type that supports mapping.

  • Internally, dictionaries are implemented as hash tables.

Here's the (now standard) list of common operations:

  • d1 = {} Empty dictionary

  • d2 = {'spam' : 2, 'eggs' : 3} Two-item dictionary

  • d3 = {'food' : {'ham' : 1, 'egg' : 2}} Nesting

  • d2['eggs'], d3['food']['ham'] Indexing by key

  • d2.has_key('eggs'), d2.keys(), d2.values() Methods: membership test, keys list, values list, etc.

  • len(d1) Length (number stored entries)

  • d2[key] = new, del d2[key] Adding/changing, deleting

Basic operations

As previously stated, you create dictionaries and access items via a key. 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 
>>> len(d2)                     # number of entries in dictionary 
>>> d2.has_key('ham')           # key membership test (1 means true) 
>>> 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', 'spam': 2, 'ham': 

To compare with lists, when adding a new object to a dictionary only requires making a new keyword and value. Lists will return an "index out-of-bounds" type 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.

Dictionary details

Sequence operations don't work.
As previously stated, dictionaries are mappings, not sequences. Because there's no order to dictionary items, functions like concatenation and slicing don't work.

Assigning to new indexes adds entries
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.

Keys can be anything immutable
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 tutorial will cover tuples, which are basically immutable lists. The final topic for these initial tutorials will be files, which should be fairly easy for most people.

Would you like to comment? This story has been viewed 33,674 times.
« Things to Avoid in C/C++ -- scanf / epilogue, Part 9 Beginning Python Tutorial (Part 6) »


Copyright © GIDNetwork™ 2001 - 2024

Another website by J de Silva

Page generated in : 0.00869 sec.