In [ 68 ]: d.keys()
Out[68]: [‘Country’, ‘Age’, ‘Profession’, ‘Name’]
In [ 69 ]: d.values()
Out[69]: [‘Germany’, 60, ‘Chancelor’, ‘Angela Merkel’]
In [ 70 ]: d.items()
Out[70]: [(‘Country’, ‘Germany’),
(‘Age’, 60),
(‘Profession’, ‘Chancelor’),
(‘Name’, ‘Angela Merkel’)]
In [ 71 ]: birthday = True
if birthday is True:
d[‘Age’] += 1
print d[‘Age’]
Out[71]: 61
There are several methods to get iterator objects from the dict object. The objects
behave like list objects when iterated over:
In [ 72 ]: for item in d.iteritems():
print item
Out[72]: (‘Country’, ‘Germany’)
(‘Age’, 61)
(‘Profession’, ‘Chancelor’)
(‘Name’, ‘Angela Merkel’)
In [ 73 ]: for value in d.itervalues():
print type(value)
Out[73]: <type ‘str’>
<type ‘int’>
<type ‘str’>
<type ‘str’>
Table 4-3 provides a summary of selected operations and methods of the dict object.
Table 4-3. Selected operations and methods of dict objects
Method Arguments Returns/result
d[k]
[k]
Item of d with key k
d[k] = x
[k]
Sets item key k to x
del d[k]
[k]
Deletes item with key k
clear
()
Removes all items
copy
()
Makes a copy
has_key
(k)
True if k is a key
items
()
Copy of all key-value pairs
iteritems
()
Iterator over all items