Dictionaries

We'll now return to dictionaries, which lie at the heart of many Python programs, including the Python interpreter itself. We briefly looked at literal dictionaries previously, seeing how they are delimited with curly braces and contain comma-separated key value pairs, with each pair tied together by a colon:

>>> urls = {'Google': 'http://google.com',
... 'Twitter': 'http://twitter.com',
... 'Sixty North': 'http://sixty-north.com',
... 'Microsoft': 'http://microsoft.com' }
>>>

A dictionary of URLs. The order of dictionary keys is not preserved, refer to the following diagram:

Figure 5.20: Dictionary

The values are accessible via the keys:

>>> urls['Twitter']
http://twitter.com

Since each key is associated with exactly one value, and lookup is through keys, the keys must be unique within any single dictionary. It's fine, however, to have duplicate values.

Internally, the dictionary maintains pairs of references to the key objects and the value objects. The key objects must be immutable, so strings, numbers and tuples are fine, but lists are not. The value objects can be mutable, and in practice often are. Our example URL map uses strings for both keys and values, which is fine.

You should never rely on the order of items in the dictionary – it's essentially random and may even vary between different runs of the same program.

As with the other collections, there's also a named constructor dict() which can convert other types to dictionaries. We can use the constructor to copy from an iterable series of key-value pairs stored in tuples, like this:

>>> names_and_ages = [ ('Alice', 32), ('Bob', 48), ('Charlie', 28),  
('Daniel', 33) ]

>>> d = dict(names_and_ages)
>>> d
{'Charlie': 28, 'Bob': 48, 'Alice': 32, 'Daniel': 33}

Recall that the items in a dictionary are not stored in any particular order, so the order of the pairs within the list is not preserved.

So long as the keys are legitimate Python identifiers it's even possible to create a dictionary directly from keyword arguments passed to dict():

>>> phonetic = dict(a='alfa', b='bravo', c='charlie', d='delta', e='echo', f='foxtrot')
>>> phonetic
{'a': 'alfa', 'c': 'charlie', 'b': 'bravo', 'e': 'echo', 'd': 'delta', 'f': 'foxtrot'}

Again, the order of the keyword arguments is not preserved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset