Retrieving items from dicts

The keys(), values(), and items() methods are good for list-processing operations using the contents of dictionaries. The pop() and popitem() methods retrieve and delete things at the same time, so they're good for processing a temporary dictionary you don't need to keep or for processing items one at a time until there aren't any more.

items()

The items() method retrieves all the key:value pairs in a dictionary and returns them as a list of tuples. Each key:value pair is a tuple.

To retrieve all the items in a dictionary, type the name of the dictionary, a dot, and items():

>>> mydict = {'bed price': '800 pounds', 'bed length': '2 feet long'} >>> print mydict.items()

[('bed length', '2 feet long'), ('bed price', '800 pounds')]

The keys() method retrieves all the keys in the dictionary. It returns a list, as shown here:

>>> print mydict.keys() ['bed length', 'bed price']

values()

The values() method retrieves all the values in the dictionary. It returns a list, as shown here:

>>> print mydict.values() ['2 foot long', '800 pounds']

popitem()

To retrieve a single key:value pair and remove it from the dict, use the popitem() method, like this:

Tip You can't use popitem() to specify which key:value pair to retrieve. It's most often used in a while loop when you want to process items one at a time until there aren't any more but you don't care what order they're processed in. TECHNICAL The popitem() method was added in Python 2.1. STUFF

poP0

To remove a key:value pair and retrieve only the value, use the pop() method and pass the key in the parentheses, like this:

Was this article helpful?

0 0

Post a comment