Break语句不会中断for循环

时间:2019-12-08 16:39:35

标签: python-3.x

我需要从一个文本文件中创建一个嵌套字典,问题是当我只需要使用内联断点时,内部循环就会使用文件中的所有断点,因为我 如果正在读入新行但未中断循环,则添加了break语句。 我在文本文件中尝试了许多其他格式,但问题仍然存在。 python代码:

def create_dictionary(filename):
    units_dict = {}
    courses_dict = {}
    with open(filename) as f:
        for units in f:
            (unit_key, unit_name) = units.split(" : ")
            for course in unit_name.split(", "):
                (course_key, course_name) = course.split(": ")
                courses_dict[course_key] = course_name

                if '\n' in course:
                    break

            units_dict[unit_key] = courses_dict
    return units_dict

文本文件格式:

first : initial1: course name1, initial2: course name2
second : initial3: course name3, initial4: course name4

预期输出:

{first:{initial1: course name1, initial2: course name2},
second:{intial3: course name3, initial4: course name4}}

实际输出:

{first:{initial1: course name1, initial2: course name2, intial3: course name3, initial4: course name4},
second:{initial1: course name1, initial2: course name2, intial3: course name3, initial4: course name4}}

我对python很陌生,所以也许我犯了一个愚蠢的错误,无论如何,如果您能帮助我,我将不胜感激。 (我发布的代码在不同的上下文中存在类似的问题)

1 个答案:

答案 0 :(得分:0)

courses_dict汇总了所有内容,您最终在units_dict中的每个条目都引用了同一词典。试试这个

def create_dictionary(filename):
    units_dict = {}
    with open(filename) as f:
        for units in f:
            (unit_key, unit_name) = units.split(" : ")
            # each entry should have a new dict
            courses_dict = {}
            for course in unit_name.split(", "):
                (course_key, course_name) = course.split(": ")
                courses_dict[course_key] = course_name

                if '\n' in course:
                    break

            units_dict[unit_key] = courses_dict
    return units_dict