I am relatively new to Python. I’m hoping someone would be kind enough to help me extract the value from “text” in the response below; so, it prints the answer, “Sacramento”.
Below, is my best attempt at doing this. However, not sure how to do it.
import os
import openai
import json
# Load your API key from an environment variable or secret management service
openai.api_key = "----------------------------------------"
response = openai.Completion.create(
engine="davinci-codex",
prompt="Q: What is the capitol of California?\nA:",
temperature=0,
max_tokens=100,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["\n"]
)
json_object = json.loads(str(response))
print(json_object['choices']['test'])
That return value is a list, not another dictionary. You must access a list with an index value (in this case, 0). So doing json_object[‘choices’][0] returns the dictionary object:
You are very close! Your first bullet point is backwards. Lists are enclosed in square brackets while dictionaries are enclosed in curly brackets:
list_obj = ["This", "is","a","list"]
print(list_obj[0]) # Prints "This"
dict_obj = {"key1":"value1","key2":"value2"}
print(dict_obj['key2']) # Prints "value2"
You are correct in saying that list items are specified by their respective index numbers and that json_object[‘choices’] returns a list where the element at index 0 is a dictionary object. Good job! Let me know if you have questions on anything else!