Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 10 · Diccionarios · Lesson 03

Claves que faltan: in y get()

get() da un valor de reemplazo cuando la clave no existe.

Lesson content is in Spanish.

Python in your browser

The first time, Python downloads about 5 MB (only once; then it stays saved). If you can, use Wi-Fi.

Python is already saved in this browser: it will not download again.

Python downloads when you start reading.
  1. 01Understand
  2. 02Try
  3. 03Explain

The situation

Los perfiles de usuario no siempre están completos: a algunos les falta el nombre, a otros los puntos acumulados o el plan contratado. Leer con corchetes una clave que no existe detiene el programa.

Understand each piece

  • KeyError

    Es el error que aparece al leer con corchetes una clave que no existe: perfil["plan"] en un perfil sin plan.

  • "clave" in perfil

    Pregunta si la clave existe y responde True o False.

  • perfil.get("clave", reemplazo)

    Devuelve el valor de la clave si existe. Si no existe, devuelve el reemplazo, sin error. Si la clave existe y vale 0, get devuelve 0, no el reemplazo.

Example

perfil = {"nombre": "Sam"}
print("puntos" in perfil)
print(perfil.get("puntos", 0))
print(perfil.get("nombre", "sin nombre"))

El perfil no tiene la clave puntos: in da False y get devuelve el reemplazo, 0. La clave nombre sí existe, así que get devuelve Sam.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
ficha = {"producto": "cable", "stock": 0}
print(ficha.get("stock", 10))

Your mission

Mostrá un perfil incompleto

La prueba crea perfil, un diccionario al que le pueden faltar las claves "nombre", "puntos" y "plan". Mostrá estas tres líneas usando get con estos reemplazos: sin nombre, 0 y gratuito. Con {"nombre": "Leo"}, la salida es: Nombre: Leo Puntos: 0 Plan: gratuito

  1. nombre = perfil.get("nombre", "sin nombre").
  2. puntos = perfil.get("puntos", 0) y plan = perfil.get("plan", "gratuito").
  3. Mostrá las tres líneas con f-strings.

If you get stuck

One hint at a time: the first points the way and the last almost solves it.

The key idea

get(clave, reemplazo) lee una clave sin riesgo: si falta, devuelve el reemplazo.

Solve with help

If you have already tried, you can see a reference solution. The lesson is marked as solved with help and adds no XP.