Show how to create a Python dictionary and use the main operations on it.
A dictionary maps keys to values. It is created with a literal, and the usual operations are assignment, lookup, deletion and membership.
user = {"name": "Ada", "role": "engineer", "active": True}
print(user["name"]) # Ada
print(user.get("role")) # engineer
print(len(user)) # 3
user["team"] = "platform" # add a new key
user["role"] = "lead" # update an existing one
print(user["role"]) # lead
del user["active"] # remove a key
print("active" in user) # False
print(sorted(user.keys())) # ['name', 'role', 'team']Assignment with square brackets both adds and updates — if the key is new it is created, if it already exists the value is replaced. Deleting a key that does not exist raises a KeyError, whereas the in operator is always safe and is the right way to test for presence.
Two things about the dictionary itself are worth stating. The keys must be hashable, so strings, numbers and tuples of hashable values work, but a list cannot be a key. And the dictionary preserves insertion order, which is why sorted(user.keys()) is needed if you want alphabetical order rather than the order the keys were added.
The get method is the safe alternative to square-bracket access, and it returns a default instead of raising when the key is missing. That single difference is the subject of its own question, but it is worth mentioning here as the first thing to reach for when you are not certain a key exists.