Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
PYTHON DATA / CHAPTER 02 / Learn / LESSON 03
Third Data class. You can already create a dictionary and read a value by key. Now the dictionary will change.
Assignment such as profile["weight"] = 75.0 updates an existing key. If the key does not exist, the same syntax adds it: profile["active"] = True.
The items() method yields key-value pairs. You can walk them:
for key, value in profile.items():
print(key, value)This lets the code work when a dictionary gains fields. Fields retain insertion order, but most logic should not depend on that order.
Mini example:
book = {"title": "Dune", "copies": 2} book["copies"] = 3 book["available"] = True for key, value in book.items(): print(key, value)
Common mistakes: building a completely new dictionary instead of updating a key, or forgetting the parentheses on items().
Assignment by key updates or adds a field; items() yields key-value pairs.
PROFILE IDLE
›