O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dictionaries

A dictionary is an associative array or hash table that contains objects indexed by keys. You 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 Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required