Extracting a value

There are two ways of extracting a value based on a dictionary key. The best option depends on a couple of factors:

• If you're certain the key is in the dictionary, or if you want to raise a KeyError exception when the key is not in the dictionary, use the square brackets syntax.

• If many of the keys you're searching for aren't in the dictionary, or if you want Python to return a value you specify rather than raise an exception when keys aren't found, use the get() method.

To raise an exception on failure

If you want to raise an exception if the key you're searching for doesn't exist, type the name of the dict followed by a key in square brackets, like this:

>>> mydict['jane eyre'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'jane eyre'

To return a value you specify on failure

To return a default value if the key doesn't exist, follow these steps:

Was this article helpful?

0 0

Post a comment