字典填充了相同的值

时间:2019-05-07 20:48:28

标签: python python-3.x dictionary xlrd

我有一张桌子,在这里我可以获取所有信息以填充所有这些字典,但是最后所有键都具有相同的值。为什么会这样呢?如何解决?

book = xlrd.open_workbook("1k.xlsx")
sheet = book.sheet_by_index(0)
num_cols = sheet.ncols
num_rows = sheet.nrows
groups_list = []
for col_index in range(num_cols):
    group_cell = str(sheet.cell(1, col_index).value)
    if "-18" in group_cell:
        groups_list.append(group_cell)
groups_list = dict.fromkeys(groups_list, [
        dict.fromkeys(["ПОНЕДЕЛЬНИК", "ВТОРНИК", "СРЕДА", "ЧЕТВЕРГ", "ПЯТНИЦА", "СУББОТА"], dict.fromkeys(["1 пара", "2 пара", "3 пара", "4 пара", "5 пара", "6 пара"], dict.fromkeys(["Предмет", "Преподаватель", "Аудитория", "Вид занятия"]))),
        dict.fromkeys(["ПОНЕДЕЛЬНИК", "ВТОРНИК", "СРЕДА", "ЧЕТВЕРГ", "ПЯТНИЦА", "СУББОТА"], dict.fromkeys(["1 пара", "2 пара", "3 пара", "4 пара", "5 пара", "6 пара"], dict.fromkeys(["Предмет", "Преподаватель", "Аудитория", "Вид занятия"])))])

for col_index in range(num_cols):
        for group in groups_list.keys():
                if group == str(sheet.cell(1, col_index).value):
                        row_index = 3
                        for day, couples in groups_list[group][0].items():
                                for couple in couples.keys():
                                        groups_list[group][0][day][couple]['Предмет'] = str(sheet.cell(row_index, col_index).value)
                                        groups_list[group][0][day][couple]['Вид занятия'] = str(sheet.cell(row_index, col_index+1).value)
                                        groups_list[group][0][day][couple]['Преподаватель'] = str(sheet.cell(row_index, col_index+2).value)
                                        groups_list[group][0][day][couple]['Аудитория'] = str(sheet.cell(row_index, col_index+3).value)
                                        row_index += 2

在最后一个循环中,我输出了分配给该键的信息,但是,如果在其他循环中或循环之外输出,则输出将不正确

1 个答案:

答案 0 :(得分:0)

问题出在dict.fromkeys()中。因此,所有键都具有相同的引用