基于课后活动文本数据构建嵌套字典课程目录的技术咨询
Got it, let's walk through how to turn that flat text into the nested dictionary you're after. I'll share a working Python solution first, then break down the key technical bits so you understand what's going on under the hood.
First, here's the code that does the conversion:
# Your raw input text raw_text = "Swimming,20,Monday,15,Monday,17,Wednesday,18,Friday,15 Football,20,Tuesday,18,Wednesday,17,Wednesday,18,Thursday,19 Ballet,40,Monday,18,Tuesday,18,Wednesday,16,Thursday,16,Friday,17" # Split the text into separate course entries (split on spaces) course_entries = raw_text.split(' ') # Initialize the main dictionary to hold all courses course_directory = {} for entry in course_entries: # Split each course's details into individual components parts = entry.split(',') # Pull out the course name and price (first two elements) course_name = parts[0] monthly_price = parts[1] # The rest are date-time pairs we need to group date_time_elements = parts[2:] # Set up the sub-dictionary for dates and times schedule = {} # Iterate over the elements two at a time (date followed by time) for i in range(0, len(date_time_elements), 2): day = date_time_elements[i] time = date_time_elements[i+1] # If the day is already in the schedule, add the time to its list if day in schedule: schedule[day].append(time) # If not, create a new list with this time else: schedule[day] = [time] # Add the course to our main directory course_directory[course_name] = { 'Price': monthly_price, 'Dates': schedule } # Check the result print(course_directory)
Key Technical Points to Note:
- String Parsing Basics: We use
split(' ')to break the big text block into individual course strings, thensplit(',')to tear each course into its core details. This is how we turn unstructured text into structured data we can work with. - Pairwise Iteration: The
range(0, len(date_time_elements), 2)trick lets us step through the date and time elements in pairs—critical because each date is followed immediately by its corresponding time in the raw data. - Handling Duplicate Days: For days that show up multiple times (like Monday for Swimming), we check if the day already exists in the
scheduledict. If it does, we append the new time to the existing list instead of overwriting it. This ensures we capture all times for each day. - Nested Dictionary Building: We build the structure layer by layer: first the inner
scheduledict for each course's dates/times, then wrap that with the price into a sub-dictionary, which we add to the maincourse_directoryusing the course name as the key.
内容的提问来源于stack exchange,提问作者meriam
相关产品推荐
相关产品推荐

