Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Dictionaries | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137110162165014051008045182

### Dictionaries

A dictionary is an associative array or hash table that contains objects indexed by keys. Create a dictionary by enclosing the values in curly braces (`{ }`) like this:

    a = {
           "username" : "beazley",
           "home" : "/home/beazley",
           "uid" : 500
        }

To access members of a dictionary, use the key-indexing operator as follows:

    u = a["username"]
    d = a["home"]

Inserting or modifying objects works like this:

    a["username"] = "pxl"
    a["home"] = "/home/pxl"
    a["shell"] = "/usr/bin/tcsh"

Although strings are the most common type of key, you can use many other Python objects, including numbers and tuples. Some objects, including lists and dictionaries, cannot be used as keys, because their contents are allowed to change.

Dictionary membership is tested with the `has_key()` method, as in the following example:

    if a.has_key("username"):
         username = a["username"]
    else:
         username = "unknown user"

This particular sequence of steps can also be performed more compactly as follows:

    username = a.get("username", "unknown user")

To obtain a list of dictionary keys, use the `keys()` method:

    k = a.keys()            # k = ["username","home","uid","shell"]

Use the `del` statement to remove an element of a dictionary:

    del a["username"]

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.