Python datetime类函数产生错误
我正在用python 3编写一个函数,它使用photo dir条目列表pdel并生成photo name dict类型的字典,其中键是photo的文件名,值是photo类型的对象,字段大小是photo dir条目中元素的大小,字段pdate是来自照片目录条目。我编写的函数产生了一个错误:Python datetime类函数产生错误,python,class,datetime,dictionary,key-value,Python,Class,Datetime,Dictionary,Key Value,我正在用python 3编写一个函数,它使用photo dir条目列表pdel并生成photo name dict类型的字典,其中键是photo的文件名,值是photo类型的对象,字段大小是photo dir条目中元素的大小,字段pdate是来自照片目录条目。我编写的函数产生了一个错误: ## A photo-dir-entry is a list consisting of the following ## elements in order: ## - a Str representi
## 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
我最终得到了一个我应该产生的错误
{ "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`
在create_photo_name_dict中,当在for循环中创建dict时,您试图将参数作为ph_dict[entry[1]]等传递给photo。但是ph_dict最初是空的,所以这永远不会起作用,并且非常确定这也不是您想要的
只需输入条目[1]、`entry[2]等,我相信这也是您想要的-
ph_dict[entry[0]] = Photo(entry[1], entry[2], entry[3], entry[4])
这个错误是…?一个错误?你认为你可以更具体一点吗?你希望ph_dict[entry[1]到底做什么?我希望它将datetime模块的数据结构转换为一个字典
ph_dict[entry[0]] = Photo(entry[1], entry[2], entry[3], entry[4])