Show how to create a Python dictionary and use the main operations on it.
A dictionary maps keys to values. You create one with a literal, and the usual operations are assignment, lookup, deletion, and the membership test. The earlier questions in this topic covered lists and sets, and a dictionary is the structure you reach for when the items have names instead of positions.
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 key
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 does two different jobs. If the key is new, it is created. If the key already exists, the value is replaced. Deleting a key that does not exist raises a KeyError, while the in operator is always safe and is the right way to test whether a key is present.
Two things about the dictionary itself are worth stating plainly. The keys must be hashable, so strings, numbers, and tuples of hashable values all work, but a list can never be a key. And the dictionary keeps its keys in the order they were added, which is why you need sorted(user.keys()) when you want an alphabetical order rather than the order in which the keys were inserted.
The get method is the safe alternative to square-bracket access, because it returns a default value instead of raising an error when the key is missing. That single difference is the subject of its own question later in this topic, but it is worth mentioning here because it is the first thing to reach for when you are not sure that a key exists.