##language:zh ''' ''' <> == 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方法。 如果你有一个字典 {{{ #!python d = {'key':'value'} }}} You can write a test to pull out the value of 'key' from d in an exception-safe way: 在一个异常安全的方法中,你能够写一个从d中提取‘key’的值的测试 {{{ #!python if d.has_key('key'): # or, in Python 2.2 or later: if 'key' in d: print d['key'] else: print 'not found' }}} However, there is a much simpler syntax: 然而有一个更简单的方法 {{{ #!python 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. 想从一个字典获得一个值,但是首先要确信这个值是否在这个字典里?使用简单有效的get方法。 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. get是简单,有效的机制,python的文档很好的解释了它。但是不知道它的人的数量令人惊讶。这个惯用方法在zope中也是相当普遍的,比如抽取REQUEST字典的一些值的时候。 === 1.4.4 See Also === 参考 The Library Reference section on mapping types.