Devuelve Ninguno si la clave del diccionario no está disponible


Necesito una forma de obtener un valor de diccionario si su clave existe, o simplemente devolver None, si no lo hace.

Sin embargo, Python devuelve un key_error si busca una clave que no existe. Sé que puedo comprobar la llave, pero estoy buscando algo más explícito. ¿Hay alguna manera de devolver Nada si la clave no existe ?

 333
Author: mshell_lauren, 2011-05-26

11 answers

Puede utilizar get()

value = d.get(key)

Que devolverá None si key is not in d. También puede proporcionar un valor predeterminado diferente que se devolverá en lugar de None:

value = d.get(key, "empty")
 556
Author: Tim Pietzcker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-07 15:17:57

No me pregunto más. Está integrado en el lenguaje.

    >>> help(dict)

    Help on class dict in module builtins:

    class dict(object)
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
    ...
     |  
     |  get(...)
     |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
     |  
    ...
 55
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 21:37:08
 20
Author: Daenyth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 20:51:49

Debe usar el método get() de la clase dict

d = {}
r = d.get( 'missing_key', None )

Esto resultará en r == None. Si la clave no se encuentra en el diccionario, la función get devuelve el segundo argumento.

 16
Author: dusktreader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-30 23:58:40

Si desea una solución más transparente, puede subclase dict para obtener este comportamiento:

class NoneDict(dict):
    def __getitem__(self, key):
        return dict.get(self, key)

>>> foo = NoneDict([(1,"asdf"), (2,"qwerty")])
>>> foo[1]
'asdf'
>>> foo[2]
'qwerty'
>>> foo[3] is None
True
 15
Author: Björn Pollex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 21:00:24

Normalmente uso un defaultdict para situaciones como esta. Se proporciona un método de fábrica que no toma argumentos y crea un valor cuando ve una nueva clave. Es más útil cuando se quiere devolver algo así como una lista vacía en claves nuevas ( ver los ejemplos).

from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key']  # prints 'None'
 9
Author: job,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-31 19:20:56

Como otros han dicho anteriormente, puedes usar get().

Pero para buscar una clave, también puedes hacer:

d = {}
if 'keyname' in d:

    # d['keyname'] exists
    pass

else:

    # d['keyname'] does not exist
    pass
 4
Author: Marek P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 21:00:47

Podría usar un método dict del objeto get(), como otros ya han sugerido. Alternativamente, dependiendo de exactamente lo que estás haciendo, es posible que puedas usar una suite try/except como esta:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

Que se considera que es un enfoque muy "pitónico" para manejar el caso.

 4
Author: martineau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 22:07:23

Una solución de una línea sería:

item['key'] if 'key' in item else None

Esto es útil cuando se intenta agregar valores de diccionario a una nueva lista y se desea proporcionar un valor predeterminado:

Eg.

row = [item['key'] if 'key' in item else 'default_value']
 1
Author: imapotatoe123,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 18:20:12

Si puedes hacerlo con False, entonces, también está el hasattr función incorporada:

e=dict()
hasattr(e, 'message'):
>>> False
 -1
Author: Evhz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 14:35:42

Puede anular __missing__(self, key) mediante la subclase dict y devolver None.

class MyDict(dict):
    def __missing__(self, key):
        return None
 -2
Author: Prashant Nair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 18:01:48