Python assistance needed with extracting answer from Q & A response

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

  "choices": [
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Sacramento"
  "created": 1633463749,
  "id": "cmpl-3pkpRFiccXlsbRiXce5GoluRzE5Hc",
  "model": "davinci-codex:2021-08-03",
  "object": "text_completion"

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(
  prompt="Q: What is the capitol of California?\nA:",

json_object = json.loads(str(response))

Welcome to the community, @MKANET! I see what you are trying to do and you’re almost there!

When you print(json_object[‘choices’]), you see that it prints a list below:

# print(json_object[‘choices’])
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Sacramento"

# print(type(json_object[‘choices’]))
<class 'list'>

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:

# print(json_object[‘choices’][0])
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Sacramento"
# print(type(json_object[‘choices’][0]))
<class 'dict'>

And with that, you can now access the ‘text’ key within that dictionary to get the correct value!

The code I believe you’re looking for is:

Let me know if that works for you!

1 Like

Thank you so much for your time and extremely helpful response. I got exactly what I wanted! This is such a friendly forum; even for novices like me.

Based on what you said (and my education); would the following statements be true?

  • Lists are enclosed in curly brackets and dictionaries are enclosed in square brackets.

  • List items are specified by their respective index numbers.

  • Choices is a list containing a single dictionary object with an index of 0.


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!