Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

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.

Example
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

Example
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

Example
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.

Example
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

Example
for key, value in ticket.items():
    print(key, "=", value)

items gives each key with its value, in the order they were added.

Try it yourself
  • Add a "priority" key with the value 4 and run the get lines again.
  • Print list(ticket.keys()).
  • Print "text" in ticket. On a dictionary, in checks the keys.

Slow is fine. Stopping is the only problem.