key not found in dictionary

Fredrik Lundh fredrik at pythonware.com
Wed Aug 23 01:11:45 EDT 2006


Ben Finney wrote:

> In the specific use case of wanting a default value when a dictionary
> doesn't have a particular key, you can also use this:
> 
>     >>> foo = {0: "spam", 1: "eggs", 7: "beans"}
>     >>> for key in [1, 2, 7]:
>     ...     desc = foo.get(key, None)

usually spelled

      desc = foo.get(key) # returns None if not present

or

      desc = foo.get(key, default)

if you want something other than None.

</F>




More information about the Python-list mailing list