根据输入的用户输入创建和打印字典内容

时间:2018-09-05 17:44:45

标签: python-3.x list dictionary

我学习了列表,元组和字典以及条件语句的基本概念。并开始编写简单的代码来接受用户输入并根据输入的内容创建字典并打印字典内容。

代码已编写-

patientCount = 0

noOfPatients = input("\nHow many Patient's to Admit: ")

while (patientCount < int(noOfPatients)):
    print("\nEnter the Details of the Patient {} :".format(patientCount+1))
    patientFirstName = input("{:>30}".format("Enter the FIRST NAME: "))
    patientLastName = input("{:>30}".format("Enter the LAST NAME: "))
    patientMRN = input("{:>30}".format("Enter the MRN: "))
    patientGender = input("{:>30}".format("Enter the GENDER (M/F/O): "))
    patientBirthYear = input("{:>30}".format("Enter the BIRTH YEAR: "))
    patientAge = input("{:>30}".format("Enter the AGE: "))

    patientCount +=1

控制台输出:

How many Patient's to Admit ?: 2

Enter the Details of the Patient 1 :

    Enter the FIRST NAME: David
     Enter the LAST NAME: John
           Enter the MRN: 878783
Enter the GENDER (M/F/O): M
Enter the BIRTH YEAR (YYYY): 1901
          Patient AGE is: 117 Years
-------------------------

Enter the Details of the Patient 2 :

    Enter the FIRST NAME: Sam
     Enter the LAST NAME: Tommy
           Enter the MRN: 76487236
Enter the GENDER (M/F/O): F
Enter the BIRTH YEAR (YYYY): 1990
          Patient AGE is: 28 Years

将初始空字典创建为-

patientDatabase = {}

我想从上面在代码中输入的输入中创建嵌套字典,如下所示:

patientDatabase = { 
Patient 1:{'First Name':'David', 'Last Name': 'John', 
'MRN': 878783, 'Gender': 'M', BirthYear': 1901, 'Age': 117}, 
Patient2:{'First Name':'Sam', 'Last Name': 'Tommy', 
'MRN': 76487236, 'Gender': 'F', BirthYear': 1990, 'Age': 28} }

当上面的字典被打印时,我正在寻找的输出如下-

Patient 1 Details:
--------------------
FIRST NAME: David
 LAST NAME: John
       MRN: 878783
    GENDER: M
BIRTH YEAR: 1901
       AGE: 117 Years

Patient 2 Details:
--------------------
FIRST NAME: Sam
 LAST NAME: Tommy
       MRN: 76487236
    GENDER: F
BIRTH YEAR: 1990
       AGE: 28 Years

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

    noOfPatients = input("\nHow many Patient's to Admit: ")
    patient_db=dict()
    for i in range(int(noOfPatients)):
        patien_details=dict()    
        print("\nEnter the Details of the Patient {} :".format(patientCount+1))
        patien_details["FirstName"] = input("{:>30}".format("Enter the FIRST NAME: "))
        patien_details["LastName"] = input("{:>30}".format("Enter the LAST NAME: "))
        patien_details["MRN"] = input("{:>30}".format("Enter the MRN: "))
        patien_details["Gender"] = input("{:>30}".format("Enter the GENDER (M/F/O): "))
        patien_details["BirthYear"] = input("{:>30}".format("Enter the BIRTH YEAR: "))
        patien_details["Age"] = input("{:>30}".format("Enter the AGE: "))
        patient_db[i+1]=patien_details

    for k,v in patient_db.items():
        print(k,v)