items
that returns a sequence of tuples, where each tuple is a key-value pair.>>> d = {'a':0, 'b':1, 'c':2} >>> t = d.items() >>> t dict_items([('c', 2), ('a', 0), ('b', 1)])
dict_items
object, which is an iterator that iterates the key-value pairs. You can use it in a for loop like this:>>> for key, value in d.items(): ... print(key, value) ... c 2 a 0 b 1
>>> t = [('a', 0), ('c', 2), ('b', 1)] >>> d = dict(t) >>> d {'a': 0, 'c': 2, 'b': 1}
dict
with zip
yields a concise way to create a dictionary:>>> d = dict(zip('abc', range(3))) >>> d {'a': 0, 'c': 2, 'b': 1}
update
also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.last
, first
and number
,
we could write:directory[last, first] = number
for last, first in directory: print(first, last, directory[last,first])
directory
, which are tuples. It assigns the elements of each tuple to last
and first
, then prints the name and
corresponding telephone number.('Cleese', 'John')
would appear as in Figure 12.1.
Figure 12.1: State diagram.
But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear as in Figure 12.2.
Figure 12.2: State diagram.
Here the tuples are shown using Python syntax as a graphical shorthand. The telephone number in the diagram is the complaints line for the BBC, so please don’t call it.