1.4 Getting a Value from a Dictionary


Credit: Andy McKay

1.4.1 Problem


You need to obtain a value from a dictionary, without having to handle an exception if the key you seek is not in the dictionary.


1.4.2 Solution

That's what the get method of dictionaries is for. Say you have a dictionary:

那就是字典的get方法。 如果你有一个字典

   1 d = {'key':'value'}

You can write a test to pull out the value of 'key' from d in an exception-safe way:


   1 if d.has_key('key'):              # or, in Python 2.2 or later: if 'key' in d:
   2     print d['key']
   3 else:
   4     print 'not found'

However, there is a much simpler syntax:


   1 print d.get('key', 'not found')

1.4.3 Discussion


Want to get a value from a dictionary but first make sure that the value exists in the dictionary? Use the simple and useful get method.


If you try to get a value with a syntax such as d[x], and the value of x is not a key in dictionary d, your attempt raises a KeyError exception. This is often okay. If you expected the value of x to be a key in d, an exception is just the right way to inform you that you're wrong (i.e., that you need to debug your program).

如果你试着用象d[x]那样的语法来获得一个值,并且x的值不是字典d的键值, 你的尝试将抛出一个KeyError异常。 这个是经常有用的。如果你期望x的值是d中的一个键值,一个异常是通知你犯错了的正确途径。(那就是说,你需要调试你的程序了)

However, you often need to be more tentative about it: as far as you know, the value of x may or may not be a key in d. In this case, don't start messing with the has_key method or with try/except statements. Instead, use the get method. If you call d.get(x), no exception is thrown: you get d[x] if x is a key in d, and if it's not, you get None (which you can check for or propagate). If None is not what you want to get when x is not a key of d, call d.get(x, somethingelse) instead. In this case, if x is not a key, you will get the value of somethingelse.

然而,关于它,你经常需要更多的假设:直到你知道x的值或者是或者不是d中的一个键值。在这种情况下,忘掉has_key方法或者try/except语句。 取而代之的,使用get方法。如果你调用d.get(x),没有异常被抛出。如果x是d的一个键值,你得到d[x]。如果不是,你得到None(你能检查或者传播它)。 当x不是d的键值的时候,如果None不是你想要的,调用d.get(x, somethingelse)来替代。在这种情况下,如果x不是一个键值。你将得到somethingelse的值

get is a simple, useful mechanism that is well explained in the Python documentation, but a surprising number of people don't know about it. This idiom is also quite common in Zope, for example, when pulling variables out of the REQUEST dictionary.


1.4.4 See Also


The Library Reference section on mapping types.

PyCkBk-1-4 (last edited 2009-12-25 07:15:34 by localhost)