#๐Ÿ”’ Need help understand how to retrieve items from nest dictionary

12 messages ยท Page 1 of 1 (latest)

obsidian prism
#

Hello I am trying to access the values in a dict that I will load from a json file. This is all from a function that I made where the variable subject takes in the input of the subject the user wants to study and creates the key for it if it doesn't exist. I did the same thing for the variable chapter and it's value is a list of tuples that has the variable question and answer.

{
    "Sec+": {
        "Chapter 1": [
            [
                "What is a VPN?",
                "Virtual Private Network"
            ],
            [
                "What is an IDS?",
                "Intrusion Detection System"
            ]
        ],
        "Chapter 2": [
            [
                "What is a WAN?",
                "Wide Area Network"
            ],
            [
                "What is a DNS?",
                "Domain Name Services"
            ]
        ]
    },
    "Python": {
        "Chapter 1": [
            [
                "What statement creates a function",
                "A def statement"
            ],
            [
                "What happens to variables in a local scope when the function call returns?",
                "They get destroyed/forgotten"
            ]
           
        ]
    }
}```


This is my attempt to display the values of the dict

```py
def quizTaker():
    with open("practiceQuiz.json", "r") as json_QAfile:
        pracQA_Data = json.load(json_QAfile)
        print("What subject would you like to study?")
        print(", ".join(pracQA_Data.keys()))
        userInputSubject = input()
        if userInputSubject in pracQA_Data.keys():
            print(", ".join(pracQA_Data[subject][chapter]))
            print("What chapter would you like to study (or type random)")
            userInputChapter = input()
quizTaker() ```
I
dim hollowBOT
#

@obsidian prism

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

obsidian prism
#

I get this traceback error

get this traceback error

Traceback (most recent call last):
File "/Users/davesamuels/Documents/Local-Documents/Vs_Code/Python ATBSP/Practice Projects/Demo practice test.py", line 87, in <module>
quizTaker()
~~~~~~~~~^^
File "/Users/davesamuels/Documents/Local-Documents/Vs_Code/Python ATBSP/Practice Projects/Demo practice test.py", line 81, in quizTaker
print(", ".join(pracQA_Data[subject][chapter]))
^^^^^^^
NameError: name 'subject' is not defined. Did you mean: 'object'?

I don't know why the variable subject is not defined. Is it because it was defined in a function?

stray jolt
#

It's because you never define it; you called it userInputSubject

obsidian prism
#
pracQA = {}


def quizMaker():
    print("What subject are you making the practice quiz for?")
    subject = input().strip()
    print("What chapter are you making the practice quiz for?")
    chapter = input().strip()
    # Removes spaces and tabs from the beginning and end of a string

    pracQA.setdefault(subject, {}).setdefault(
        chapter, []
    )  # Sets the variable "chapter" as the key and an empty list as the value.
    # Variables that are hashable(immutable) can be used as a key in a dictionary.
    # Variables that have the data type on int, str or tuple

    while True:
        print('Input your question (or type "quit" to exit)')
        question = input().strip()
        if question.lower() == "quit":
            break

        print("Input the answer")
        answer = input().strip()

        # Append question-answer pair to the list under the chapter key
        pracQA[subject][chapter] += [(question, answer)]
        # pracQA[chapter] refers to the list inside pracQA variable. In this case the empty list []
        # {chapter:} is the key
        # pracQA[chapter] + [(question, answer)] is the string concatenation
        # [] + [(question, answer)]

    print("\nFinal Practice Quiz Data:")
    print(pracQA)
obsidian prism
# stray jolt It's because you never define it; you called it `userInputSubject`

Oh ok I understand that part now. So trying to access the first key value in the variable pracQA_Data I did so with pracQA_Data.keys() but I don't know how to access the keys that are nested within it.
For the program I had above I could navigate the dictionary with [] using the variables I had. I don't see a way to do this without explicitly naming the key like pracQA_Data["sec+"]["Chapter 1"] I want to streamline it based on user input.

#

pracQA_Data.keys() gave me "sec+", "Python" but not the keys that had the chapters in them

stray jolt
obsidian prism
stray jolt
dim hollowBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.