skip to Main Content

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


  1. This program should do what you need. Have added comments for details of what each line is doing.

    import json
    
    # defines a dictionary with a list of patients as value
    patients = {"patients": []}
    
    # initializes the info variable
    info = ""
    
    # run a loop to capture comma separated values from user until they ask to stop
    while (info != "stop"):
        info = input("Enter first name, last name, age, and gender separated by space. Enter stop to stop: ")
        if (info != "stop"):
            # splits the input by comma to form a data list
            data = info.split(",")
            # create a patient entry from the data list, using positions and trims any white spaces, converts age to number
            patient_entry = {"first_name": data[0].strip(" "), "last_name": data[1].strip(" "), "age": int(data[2]), "gender": data[3].strip(" ")}
            # adds the patient entry to the patient dictionary
            patients["patients"].append(patient_entry)
    
    
    # opens a json file to write to and dumps the dictionary content into the file as json
    json_file = open("patients.json", "w")
    json.dump(patients, json_file)
    

    This code expects that each input line is either the exact word stop or that it has four comma separated values in the exact format string, string, number, string. If you want to handle varied inputs, input validation such as below will need to be added to the code.

    • Check if the length of data is four
    • Check if the third entry is indeed a number

    The content of patients.json will look like below

    {
        "patients": [
            {
                "first_name": "John",
                "last_name": "Doe",
                "age": 45,
                "gender": "m"
            },
            {
                "first_name": "Jane",
                "last_name": "Doe",
                "age": 40,
                "gender": "f"
            }
        ]
    }
    
    Login or Signup to reply.
  2. "… How can I set my code so that a user can continue inputting info until the loop is broken? …"

    Place the code within a loop, and utilize a boolean variable.

    m = {'patients': []}
    exit = False
    while not exit:
        if (i := input()) == '': exit = True
        else:
            a, b, c, d = i.split()
            if '' in (a, b, c, d): exit = True
            else:
                m['patients'].append([
                    {'first_name': a},
                    {'last_name': b},
                    {'age': int(c)},
                    {'gender': d}
                ])
    

    Here is the output, formatted.
    Slightly different than JSON, I know.

    abc xyz 123 m
    xyz abc 321 f
    
    {'patients': 
        [
            [
                {'first_name': 'abc'}, 
                {'last_name': 'xyz'}, 
                {'age': 123}, 
                {'gender': 'm'}
            ], 
            [
                {'first_name': 'xyz'}, 
                {'last_name': 'abc'}, 
                {'age': 321}, 
                {'gender': 'f'}
            ]
        ]
    }
    

    "… 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? …"

    You would need to just format the output as JSON.

    This could be as simple as a string-format, or using a JSON module.

    Login or Signup to reply.
  3. 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.

    patients = []
    
    
    add_entry = True
    
    
    def add_patient():
        patient_dict = {}
        patient_dict["first_name"] = input("Enter first name: ")
        patient_dict["last_name"] = input("Enter last name: ")
        patient_dict["age"] = input("Enter age: ")
        patient_dict["gender"] = input("Enter gender: ")
        patients.append(patient_dict)
        return 0
    
    
    while add_entry:
        add_patient()
        add_new = input("Enter another patient (y/n): ")
        if add_new == "n":
            add_entry = False
    
    
    for patient in patients:
        print(patient)
    

    The output would look like this:

    {'first_name': 'John', 'last_name': 'Doe', 'age': '33', 'gender': 'm'}
    {'first_name': 'Jane', 'last_name': 'Smith', 'age': '21', 'gender': 'f'}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search