Python Essentials for AI

Updated · 5 min read

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

Six tools, each with real output
FeatureDescriptionExample
DictionaryIt is used to map names to values{"lab": 45}
ListIt is used to keep items in order[9, 10, 11, 12]
FunctionIt is used to name and reuse a set of stepsdef total(names): ...
ComprehensionIt is used to build a new collection in one line{n: a * 1.05 for n, a in fees.items()}
JSONIt is used to turn data into text and back, for APIs and filesjson.dumps(data), json.loads(text)
try / exceptIt is used to handle errors without crashingexcept KeyError:

Example

Python
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)
Output
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

FunctionDescription
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:

  1. What does a dictionary store?
  2. What does json.loads() return?
  3. Why catch KeyError specifically?

Quick check: Python essentials

4 questions
1What does fees["lab"] return in the example?
2What does json.dumps() do?
3What happened when the code asked for the "parking" fee?
4Which safely returns 0 for a missing key?

Key Takeaways

Quick reference

NeedUse
Look up by nameDictionary
Keep orderList
Transform a collectionComprehension
Talk to an APIjson.dumps, json.loads
Survive bad inputtry / except

Was this tutorial helpful?

Lesson 77 of 186