Python Essentials for AI
Python essentials are the small set of language features used in almost every AI project: collections to hold data, functions to organize steps, JSON to exchange data with APIs, and error handling to keep programs running. Model APIs send and receive JSON, datasets arrive as lists and dictionaries, and every real program must handle bad input.
This lesson covers the six you'll use most, with one Campus Helper example.
The Six Essentials
| Feature | Description | Example |
|---|---|---|
| Dictionary | It is used to map names to values | {"lab": 45} |
| List | It is used to keep items in order | [9, 10, 11, 12] |
| Function | It is used to name and reuse a set of steps | def total(names): ... |
| Comprehension | It is used to build a new collection in one line | {n: a * 1.05 for n, a in fees.items()} |
| JSON | It is used to turn data into text and back, for APIs and files | json.dumps(data), json.loads(text) |
| try / except | It is used to handle errors without crashing | except KeyError: |
Example
import json
fees = {"lab": 45, "field trip": 30, "library": 15} # a dictionary
grades = [9, 10, 11, 12] # a list
def total(fee_names):
"""A function: add up the fees for a list of names."""
return sum(fees[name] for name in fee_names)
with_tax = {name: round(amount * 1.05, 2) for name, amount in fees.items()} # a comprehension
print("Total for lab and library:", total(["lab", "library"]))
print("With 5% added:", with_tax)
text = json.dumps({"grade": 10, "fees": fees}) # to JSON text
print("JSON:", text)
print("Back to Python:", json.loads(text)["fees"]["lab"])
try:
total(["lab", "parking"])
except KeyError as error:
print("Unknown fee:", error)Total for lab and library: 60
With 5% added: {'lab': 47.25, 'field trip': 31.5, 'library': 15.75}
JSON: {"grade": 10, "fees": {"lab": 45, "field trip": 30, "library": 15}}
Back to Python: 45
Unknown fee: 'parking'Explanation: total() looks up each name in the fees dictionary and adds the amounts. The comprehension builds a new dictionary with 5% added to each fee. json.dumps() turns Python data into JSON text, and json.loads() turns it back. Asking for "parking", which isn't in the dictionary, raises a KeyError, which the except block catches and reports.
Reading and Writing Files
| Function | Description |
|---|---|
open(path, "w") | It is used to open a file for writing |
json.dump(data, file) | It is used to write data to a file as JSON |
json.load(file) | It is used to read JSON from a file |
with open(...) as f: | It is used to open a file and close it automatically |
Common Mistakes
Assuming a key exists. Check with in, use .get(), or catch KeyError.
Confusing JSON text with Python data. json.loads() turns the text into a dictionary you can index.
Catching every error with a bare except:. Catch the specific error you expect, so real bugs still show.
Interview Corner
What is the difference between json.dumps and json.loads?
json.dumps() turns Python data into a JSON string; json.loads() turns a JSON string into Python data. The versions without "s", dump and load, work with files.
What is a comprehension?
A compact way to build a list, dictionary or set from another collection in one expression, such as {n: a * 1.05 for n, a in fees.items()}.
Practice
Exercise: extend the fee program. Add a "sports": 60 fee, write a function most_expensive() that returns the name of the highest fee, and save the fees to fees.json with json.dump. Then read the file back with json.load and print the lab fee.
Check your understanding:
- What does a dictionary store?
- What does
json.loads()return? - Why catch
KeyErrorspecifically?
Key Takeaways
Quick reference
| Need | Use |
|---|---|
| Look up by name | Dictionary |
| Keep order | List |
| Transform a collection | Comprehension |
| Talk to an API | json.dumps, json.loads |
| Survive bad input | try / except |
Was this tutorial helpful?