Advertisement
acclivity

pyStudentDatabaseCreateAndList

Nov 16th, 2022
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1.  
  2. # Example of a student "database" using nested dictionary
  3. # Each student's data includes age, grade, and decision, and may contain multiple comments (or no comments)
  4.  
  5. students = {}
  6. name = ""
  7. heading = ""
  8.  
  9. fin = open("StudentData.txt")
  10.  
  11. for line in fin:
  12.     lista = line.split(":")
  13.     if len(lista) == 2:                 # Line has 2 sections, data heading and data value
  14.         heading = lista[0]
  15.         value = lista[1].strip()        # Everything after ":" stripped of white space
  16.         if heading == "Student":
  17.             name = value
  18.             students[name] = {}         # Create empty sub-dictionary for this student
  19.         elif heading == "Comments":
  20.             students[name][heading] = [value]       # Create list containing first comment line
  21.         else:
  22.             students[name][heading] = value
  23.     elif heading == "Comments":           # continuation of comments section
  24.         students[name][heading].append(line.strip())      # append new comment to list in dict
  25.  
  26. # print(students)       # optional print for testing purposes
  27. # print()
  28.  
  29. # Print data for all students
  30. for name in students:
  31.     age = students[name]["Age"]
  32.     grade = students[name]["Grade"]
  33.     decision = students[name]["Decision"]
  34.     comment_list = []           # set default empty comments list
  35.  
  36.     print(f"Name: {name:<12}  Age: {age:<6} Grade: {grade}")
  37.     if "Comments" in students[name]:
  38.         print("Comments:")
  39.         comment_list = students[name]["Comments"]
  40.     for comment in comment_list:
  41.         print("   ", comment)
  42.     print(f"Decision: {decision}\n")
  43.  
  44.  
  45. # OUTPUT:-
  46. # Name: David         Age: 21     Grade: 98
  47. # Comments:
  48. #     Good behaviour.
  49. #     Participated fully in music class.
  50. # Decision: Pass
  51. #
  52. # Name: Matilda       Age: 29     Grade: 100
  53. # Comments:
  54. #     Good behaviour.
  55. #     Helped friend with math problems.
  56. #     Will place in advanced math.
  57. # Decision: Pass
  58. #
  59. # Name: Rupert        Age: 19     Grade: 72
  60. # Comments:
  61. #     Lacking in concentration
  62. # Decision: Fail
  63. #
  64. # Name: George        Age: 20     Grade: 67
  65. # Decision: Fail
  66.  
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement