¿Cómo puedo comprobar si existe una clave en un diccionario? [duplicar]


Posible Duplicado:
Compruebe si una clave dada ya existe en un diccionario

Digamos que tengo una matriz asociativa como así: {'key1': 22, 'key2': 42}.

¿Cómo puedo comprobar si key1 existe en el diccionario?

 258
Author: codeforester, 2010-10-02

3 answers

if key in array:
  # do something

Los arrays asociativos se llaman diccionarios en Python y puedes aprender más sobre ellos en la documentación de stdtypes.

 466
Author: Rafał Rawicki,
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
2015-12-12 22:51:25

Otro método es has_key() (si todavía está usando Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True
 51
Author: ghostdog74,
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-07-27 12:55:32

Si desea recuperar el valor de la clave si existe, también puede usar

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

Si desea recuperar un valor predeterminado cuando la clave no existe, utilice value = a.get(key, default_value). Si desea establecer el valor predeterminado al mismo tiempo en caso de que la clave no exista, utilice value = a.setdefault(key, default_value).

 38
Author: Marc,
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
2010-10-02 12:50:27