Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Example of a student "database" using nested dictionary
- # Each student's data includes age, grade, and decision, and may contain multiple comments (or no comments)
- students = {}
- name = ""
- heading = ""
- fin = open("StudentData.txt")
- for line in fin:
- lista = line.split(":")
- if len(lista) == 2: # Line has 2 sections, data heading and data value
- heading = lista[0]
- value = lista[1].strip() # Everything after ":" stripped of white space
- if heading == "Student":
- name = value
- students[name] = {} # Create empty sub-dictionary for this student
- elif heading == "Comments":
- students[name][heading] = [value] # Create list containing first comment line
- else:
- students[name][heading] = value
- elif heading == "Comments": # continuation of comments section
- students[name][heading].append(line.strip()) # append new comment to list in dict
- # print(students) # optional print for testing purposes
- # print()
- # Print data for all students
- for name in students:
- age = students[name]["Age"]
- grade = students[name]["Grade"]
- decision = students[name]["Decision"]
- comment_list = [] # set default empty comments list
- print(f"Name: {name:<12} Age: {age:<6} Grade: {grade}")
- if "Comments" in students[name]:
- print("Comments:")
- comment_list = students[name]["Comments"]
- for comment in comment_list:
- print(" ", comment)
- print(f"Decision: {decision}\n")
- # OUTPUT:-
- # Name: David Age: 21 Grade: 98
- # Comments:
- # Good behaviour.
- # Participated fully in music class.
- # Decision: Pass
- #
- # Name: Matilda Age: 29 Grade: 100
- # Comments:
- # Good behaviour.
- # Helped friend with math problems.
- # Will place in advanced math.
- # Decision: Pass
- #
- # Name: Rupert Age: 19 Grade: 72
- # Comments:
- # Lacking in concentration
- # Decision: Fail
- #
- # Name: George Age: 20 Grade: 67
- # Decision: Fail
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement