Unit 10 · Diccionarios · Lesson 02
Modificar y agregar claves
Asignar a una clave cambia su valor o la agrega.
- Difficulty: Media
- 20 XP
- Python
- Not started
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.
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"] = valorSi la clave existe, cambia su valor. Si no existe, la agrega al final del diccionario.
Cuenta con el valor anteriorficha["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?
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}
- ficha["stock"] = ficha["stock"] - venta.
- ficha["vendidos"] = venta.
- print(ficha).
If you get stuck
One hint at a time: the first points the way and the last almost solves it.
- 1
Para cambiar un valor, asignale a esa clave: ficha["stock"] = ...
- 2
La cuenta usa el valor actual: ficha["stock"] - venta.
- 3
Después agregá ficha["vendidos"] = venta y mostrá la ficha.
The key idea
diccionario[clave] = valor cambia el valor si la clave existe y la agrega si no existe.
You passed this lesson
- Actualizaste una ficha y le agregaste un dato nuevo.
- ¿Qué pasa si leés una clave que no existe? Lo vas a ver en la próxima lección.
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.