pythoninquirer

Using inquirer in a dictionary


I am trying to make a dictionary that gets input from the user. My current code is(not finished in a long way)

person = {
  "name": str(inp("Enter your name: ")),
  "age": int(inp("Enter your age: ")),
  "gender": # Help
}

Okay, so I also wrote a small code with inquirer that gives 2 choices:

questions = [
  inquirer.List('gender',
                message="What gender are you?",
                choices=['Male', 'Female'], ),
]
answers = inquirer.prompt(questions)

This gives the user 2 alternatives in the console. Male and Female. But how do I get so my gender code is connected to the "gender" element in person?


Solution

  • Since your person object is a dictionary you can just set the gender like so:

    person["gender"] = new_value
    

    With inquirer, it seems like the .prompt() function returns a dictionary where the keys (like gender in your person dictionary) are the names of the questions (I suppose that for you it would be gender). In that case you can link the previous code with our new knowledge and write something like this:

    person["gender"] = answers["gender"]
    

    If you want to write all of the above in a more concise manner, you could try something like this:

    questions = [
      inquirer.List('gender',
                    message="What gender are you?",
                    choices=['Male', 'Female'], ),
    ]
    answers = inquirer.prompt(questions)
    
    person = {
      "name": str(inp("Enter your name: ")),
      "age": int(inp("Enter your age: ")),
      "gender": answers["gender"]
    }
    

    And of course if you want to preserve the order of questions, you can simply extract the questions for name and age like so:

    name = str(inp("Enter your name: "))
    age = int(inp("Enter your age: "))
    questions = [
      inquirer.List('gender',
                    message="What gender are you?",
                    choices=['Male', 'Female'], ),
    ]
    answers = inquirer.prompt(questions)
    
    person = {
      "name": name,
      "age": age,
      "gender": answers["gender"]
    }