Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 10 · Diccionarios · Lesson 02

Modificar y agregar claves

Asignar a una clave cambia su valor o la agrega.

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

Cada vez que se vende un producto, su ficha tiene que actualizarse: baja el stock. A veces también hay que agregar un dato nuevo, como cuántas unidades se vendieron.

Understand each piece

  • ficha["clave"] = valor

    Si la clave existe, cambia su valor. Si no existe, la agrega al final del diccionario.

  • Cuenta con el valor anterior

    ficha["stock"] = ficha["stock"] - 2 lee el stock actual, le resta 2 y guarda el resultado en la misma clave.

Example

ficha = {"producto": "monitor", "stock": 5}
ficha["stock"] = ficha["stock"] - 2
ficha["color"] = "negro"
print(ficha)

La segunda línea cambia el stock de 5 a 3. La tercera agrega la clave color, que no existía. Se muestra {'producto': 'monitor', 'stock': 3, 'color': 'negro'}.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
ficha = {"producto": "mouse", "stock": 10}
ficha["stock"] = 4
print(ficha)

Your mission

Registrá una venta

La prueba crea ficha (un diccionario con las claves "producto" y "stock") y venta (unidades vendidas, nunca más que el stock). Restá la venta del stock, agregá la clave "vendidos" con el valor de venta y mostrá la ficha. Con {"producto": "teclado", "stock": 12} y venta = 5, la salida es: {'producto': 'teclado', 'stock': 7, 'vendidos': 5}

  1. ficha["stock"] = ficha["stock"] - venta.
  2. ficha["vendidos"] = venta.
  3. print(ficha).

If you get stuck

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

The key idea

diccionario[clave] = valor cambia el valor si la clave existe y la agrega si no existe.

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.