diveintopython.org
Python for experienced programmers

 

1.7. Dictionaries 101

A short digression is in order, because you need to know about dictionaries, tuples, and lists (oh my!). If you're a Perl hacker, you can probably skim the bits about dictionaries and lists, but you should still pay attention to tuples.

One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values. This is like an associative array in Perl, a Map in Java, or the Scripting.Dictionary object in VBScript.

Example 1.9. Defining a dictionary

>>> d = {"server":"mpilgrim", "database":"master"} 1
>>> d
{'server': 'mpilgrim', 'database': 'master'}
>>> d["server"]                                    2
'mpilgrim'
>>> d["database"]                                  3
'master'
>>> d["mpilgrim"]                                  4
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
KeyError: mpilgrim
1 First, we create a new dictionary with two elements and assign it to the variable d. Each element is a key-value pair, and the whole set of elements is enclosed in curly braces.
2 server is a key, and its associated value, referenced by d["server"], is mpilgrim.
3 database is a key, and its associated value, referenced by d["database"], is master.
4 You can get values by key, but you can't get keys by value. So d["server"] is mpilgrim, but d["mpilgrim"] raises an exception, because mpilgrim is not a key.

Example 1.10. Modifying a dictionary

>>> d
{'server': 'mpilgrim', 'database': 'master'}
>>> d["database"] = "pubs" 1
>>> d
{'server': 'mpilgrim', 'database': 'pubs'}
>>> d["uid"] = "sa"        2
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
1 You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
2 You can add new key-value pairs at any time. This syntax is identical to modifying existing values. (Yes, this will annoy you someday when you think you are adding new values but are actually just modifying the same value over and over because your key isn't changing the way you think it is.)

Note that the new element (key uid, value sa) appears to be in the middle. In fact, it was just a coincidence that the elements appeared to be in order in the first example; it is just as much a coincidence that they appear to be out of order now.

Note
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; they are simply unordered. This is an important distinction which will annoy you when you want to access the elements of a dictionary in a specific, repeatable order (like alphabetical order by key). There are ways of doing this, they're just not built into the dictionary.

Example 1.11. Mixing datatypes in a dictionary

>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
>>> d["retrycount"] = 3 1
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}
>>> d[42] = "douglas"   2
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 42: 'douglas', 'retrycount': 3}
1 Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all have to be the same type; you can mix and match as needed.
2 Dictionary keys are more restricted, but they can be strings, integers, and a few other types (more on this later). You can also mix and match key datatypes within a dictionary.

Example 1.12. Deleting items from a dictionary

>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 42: 'douglas', 'retrycount': 3}
>>> del d[42] 1
>>> d
{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}
>>> d.clear() 2
>>> d
{}
1 del lets you delete individual items from a dictionary by key.
2 clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary with no items.