【发布时间】:2015-10-11 15:38:04
【问题描述】:
我正在 python 3 中编写一个函数,它使用一个 photo-dir-entry-list (pdel) 并生成一个 photo-name-dict 类型的字典,其中键是照片的文件名,值是对象类型为 Photo ,字段 size 具有 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`
【问题讨论】:
-
而错误是...?
-
an error?你认为你可以更具体吗? -
你希望
ph_dict[entry[1]]做什么,确切地说? -
我希望它能够使用它所使用的日期时间模块数据结构并将其转换为字典
标签: python class datetime dictionary key-value