我正在python 3中编写一个函数,它使用photo-dir-entry-list(pdel)并生成一个类型为photo-name-dict的字典,其中key是照片的文件名,值是对象类型为Photo的字段大小具有photo-dir-entry中元素的大小,而字段pdate具有来自photo-dir-entry的元素的日期。我写的函数产生错误:
## A photo-dir-entry is a list consisting of the following
## elements in order:
## - a Str representing the filename of the photo
## - an Int[>=1] representing the size of the photo file
## - an Int representing the year the photo was taken
## - an Int[1<=,<=12] representing the month the photo was taken
## - an Int[1<=,<=31] representing the day the photo was taken
## The Date elements contain a valid date.
## A photo-dir-entry-list is a list of photo-dir-entries with unique filenames.
## A Photo is an object consisting of two fields
## - size: an Int[>0] representing the size of the file
## - pdate: a Date representing the date the photo was taken
class Photo:
'Fields: size, pdate'
## Purpose: constructor for class Photo
## __init__: Int Int Int Int -> Photo
## Note: Function definition needs a self parameter and does not require a return statement
def __init__(self, size, year, month, day):
self.size = size
self.pdate = date(year, month, day)
## Purpose: Produces a string representation of a Photo
## __repr__: Photo -> Str
def __repr__(self):
s1 = "SIZE: " + str(self.size)
s2 = "; DATE: " + self.pdate.isoformat()
return s1 + s2
def create_photo_name_dict(pdel):
ph_dict = {}
for entry in pdel:
ph_dict[entry[0]] = Photo(ph_dict[entry[1]], ph_dict[entry[2]], ph_dict[entry[3]], ph_dict[entry[4]])
return ph_dict
当我调用该函数时:
create_photo_name_dict([["DSC315.JPG",55,2011,11,13],
["DSC316.JPG",53,2011,11,12]])
我最终会出错,我应该在哪里制作
{ "DSC315.JPG": Photo(55,2011,11,13),
"DSC316.JPG": Photo(53,2011,11,12)}
错误是:
`Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 2, in <module>
if __name__ == '__main__':
File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 56, in create_photo_name_dict
builtins.KeyError: 55`
答案 0 :(得分:1)
在create_photo_name_dict()
中,在for
循环中创建字典时,您尝试将参数传递给Photo
作为ph_dict[entry[1]]
等。但ph_dict最初是空的,所以这永远不会奏效(而且很确定这不是你想要的。
只需发送entry[1]
,`条目[2]等,我相信这也是你想要的 -
ph_dict[entry[0]] = Photo(entry[1], entry[2], entry[3], entry[4])