The
for
Statement. We can't meaningfully iterate through the elements in a
dict, since there's no implicit order. Worse,
it isn't obvious that we want to iterate through the keys or through
the values in the dict.
Consequently, we have three different ways to visit the elements
in a dict, all based on three
dict method functions. Here are the
choices:
-
The key:value pairs. We can use the
items method to iterate through the
sequence of 2-tuples that contain each key and the associated
value.
-
The keys. We can use the keys method
to iterate through the sequence of keys.
-
The values. We can use the values
method to iterate throught he sequence of values in each key:value
pair.
Here's an example of using the key:value pairs. This relies on the
tuple-based
for
statement that
we looked at in the section called “Tuple Statements”. We'll iterate
through the dict, update it, and iterate through
it a second time. In this case, coincidentally, the new key-value pair
wound up being shown at the end of the
dict.
>>>
myBoat = { "NAME":"KaDiMa", "LOA":18,
"SAILS":["main","jib","spinnaker"] }
>>>
for key,value in myBoat.items():
... print key, " = ", value
LOA = 18
NAME = KaDiMa
SAILS = ['main', 'jib', 'spinnaker']
>>>
myBoat['YEAR']=1972
>>>
for key,value in myBoat.items():
... print key, " = ", value
LOA = 18
NAME = KaDiMa
SAILS = ['main', 'jib', 'spinnaker']
YEAR = 1972
The
del
Statement. The
del
statement removes items from a
dict. For example
>>>
i = { "two":2, "three":3, "quatro":4 }
>>>
del i["quatro"]
>>>
print i
{'three': 3, 'two': 2}
In this example, we use the key to remove the item from the
dict.
The member function, pop, does this
also.