dict_student[id]=[item[1]]和dict_student[id].append(item[1])之



我正在努力理解以下代码。dict_student[id] = [item[1]]dict_student[id].append(item[1])之间有什么区别?如果在字典中找不到id,则添加哪个部分?

代码:

for item in items:
id, score = item[0], item[1]
if not id in dict_student:
dict_student[id] = [item[1]]
else:
dict_student[id].append(item[1])

在字典中,条目的类型可以是list。使用append添加到列表中。

for item in items:
id, score = item[0], item[1]
if not id in dict_student:  #  if dictionary does not contain this key
dict_student[id] = [item[1]]  # create the entry (a list)
else:
dict_student[id].append(item[1])  # add item to the existing list

dict_student[id] = [item[1]]不假设id已经是字典的键。如果id已经是字典中的一个键,您将更改它的任何值并用[item[1]]覆盖它,如果它不在字典中,您将创建键id并将值[item[1]]关联到该键

dict_student[id].append(item[1])假设字典中已经有一个关键字id,如果没有,它将引发一个KeyError,它进一步假设与关键字id相关联的对象具有append方法。

最新更新