Dictionaries

The dict type is a data dictionary, also known as an associative array. A dictionary holds a set of unordered key-value pairs and provides very fast key lookup. Keys are unique and must be of an immutable type, such as a Python string, a number, or a tuple; the value can be of any type including collection types, so it is possible to create arbitrarily nested data structures. Although dictionaries are not sequences, we can get sequences of their keys and values, as we will see in the next chapter.

Similar data structures exist in other languages—for example, Perl's hash, Java's HashMap, and C++'s unordered_map.

Notice that a tuple can be a dictionary key, but a list cannot, since a dictionary's keys must be immutable. In languages that offer only simple keys like strings and numbers, programmers who want multi-item keys must resort to converting their items into a string, but thanks to tuples this kind of hack is not necessary in Python.

Here are some examples that show how to create a dictionary and access items in it:

>>> insects = {"Dragonfly": 5000, "Praying Mantis": 2000, "Fly": 120000, "Beetle": 350000} >>> insects

{'Fly': 120000, 'Dragonfly': 5000, 'Praying Mantis': 2000,

'Beetle': 350000}

5000

>>> insects["Grasshopper"] = 20000 >>> insects

{'Fly': 120000, 'Dragonfly': 5000, 'Praying Mantis': 2000, 'Grasshopper': 20000, 'Beetle': 350000}

Items can be deleted from a dictionary in the same way they can be deleted from a list. For example:

>>> del insects["Fly"] >>> insects

{'Dragonfly': 5000, 'Praying Mantis': 2000, 'Grasshopper': 20000,

'Beetle': 350000}

350000

{'Dragonfly': 5000, 'Praying Mantis': 2000, 'Grasshopper': 20000}

Table 1.5 Selected Dictionary Methods and Functions

d.values()

d.setdefault(k, x)

Description

Returns True if item x is in dict d

Returns True if x is not in dict d

Returns the number of items in dict d

Removes all items from dict d

Returns a shallow copy of dict d

Returns a list of all the keys in dict d

Returns a list of all the values in dict d

Returns a list of tuples of all the (key, value) pairs in dict d

Returns the value with key k, or None

Returns the value with key k if k is in dict d; otherwise, returns x

The same as the get() method, except that if the key is not in dict d, a new item is inserted with the given key and a value of None or x if x is given

Returns and removes the item with key k; raises a KeyError exception if there is no such key in dict d

Returns and removes the item with key k if k is in dict d; otherwise, returns x

Dictionaries can be constructed using the dict() constructor, and if the keys happen to be valid identifiers (i.e., alphanumeric beginning with an alphabetic character and with no whitespace), we can use a more convenient syntax:

>>> vitamins = dict(B12=1000, B6=250, A=380, C=5000, D3=400) >>> vitamins

{'A': 380, 'C': 5000, 'B12': 1000, 'D3': 400, 'B6': 250}

We mentioned earlier that dictionary keys can be tuples; here is one last example to show this in action:

>>> points3d = {(3, 7, -2): "Green", (4, -1, 11): "Blue", (8, 15, 6): "Yellow"} >>> points3d

{(4, -1, 11): 'Blue', (8, 15, 6): 'Yellow', (3, 7, -2): 'Green'}

'Yellow'

In Chapter 2 we will see how to iterate over dictionaries in their "natural" arbitrary order, and also in key order.

Was this article helpful?

0 0
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment