I am trying to create a dictionary that I can serialize into a json file. This is my first time trying this so I am very confused.
I want user input for a patient’s first name, last name, age, and gender so the dictionary output would be as follows:
"patients": [
{
"first_name": "Jane",
"last_name": "Doe",
"age": 33,
"gender": f,
}
]
}
I want each user input to be in one line until the loop is broken.
So far I only have:
patients = {}
info = input("Enter first name, last name, age, and gender separated by space. Enter stop to stop:")
for key, value in patients.items():
print('first_name: {}, last_name: {}, age: {}, gender: {}'. format(key, value))
How can I set my code so that a user can continue inputting info until the loop is broken? How can I make the dictionary output as shown above so that each of the inputs is separated and appear as values to the dictionary keys accordingly? I honestly am not sure where to begin and any help is appreciated!
3
Answers
This program should do what you need. Have added comments for details of what each line is doing.
This code expects that each input line is either the exact word
stop
or that it has four comma separated values in the exact formatstring, string, number, string
. If you want to handle varied inputs, input validation such as below will need to be added to the code.data
is fourThe content of patients.json will look like below
Place the code within a loop, and utilize a boolean variable.
Here is the output, formatted.
Slightly different than JSON, I know.
You would need to just format the output as JSON.
This could be as simple as a string-format, or using a JSON module.
First, it looks like you want a list with a set of dictionaries inside, so I have update the patients variable to a list.
Second, you can use a while loop to continue prompt for user input. For each entry, you can append the new dictionary to the list.
Last, to print each dictionary on one line, you can loop through the patients list and output each dictionary item.
The output would look like this: