Dictionaries: values with names
A ticket is more than its text: it has an id and a customer too. A dictionary keeps several values together and gives each one a name, called a key.
ticket = {"id": 1, "customer": "Asha", "text": "I was charged twice for one order"}
print(ticket["text"])
print(ticket["customer"])Curly brackets make a dictionary. Each entry is a key, a colon, and a value. You read a value by putting its key in square brackets, the way a list takes a position.
Adding and changing
ticket["category"] = "billing"
ticket["customer"] = "Asha K."
print(ticket)Storing under a key that does not exist adds it. Storing under one that does replaces the value. A key appears only once in a dictionary.
A key that is not there
print(ticket["priority"])A missing key is a KeyError. When a key may or may not be there, use get, which gives back a value you choose instead of stopping the program.
print(ticket.get("priority"))
print(ticket.get("priority", 3))
print(ticket.get("customer", "unknown"))None is Python's value for nothing here. get gives it back when you do not name a default.
Looping over a dictionary
for key, value in ticket.items():
print(key, "=", value)items gives each key with its value, in the order they were added.
- Add a
"priority"key with the value 4 and run thegetlines again. - Print
list(ticket.keys()). - Print
"text" in ticket. On a dictionary,inchecks the keys.
Slow is fine. Stopping is the only problem.