Python 从字典中将图像按日期排序到列表中

Python 从字典中将图像按日期排序到列表中,python,python-3.x,Python,Python 3.x,我知道我以前问过这个问题,但我仍然不知道为什么我测试这个时会得到一个空列表 def sorted_images(image_dict): '''(dict) -> list of str Given an image dictionary return a list of the filenames sorted by date. >>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], \ 'ima

我知道我以前问过这个问题,但我仍然不知道为什么我测试这个时会得到一个空列表

def sorted_images(image_dict):
'''(dict) -> list of str

Given an image dictionary return a list of the filenames
sorted by date. 

>>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], \
'image2.jpg': ['UTSC', '2017-11-04', 'Happy Sat.']}
>>> sorted_images(d)    
['image1.jpg', 'image2.jpg']
'''
new_list = []
for filename, (location, date, caption) in image_dict.items():
    if filename not in image_dict:
        new_list.append(filename)
return new_list

您的列表为空,因为此条件始终为false

if filename not in image_dict:
filename
image\u dict
中的一个键

要获取docstring中指定的输出,可以执行以下操作:

def sorted_images(image_dict):

    '''(dict) -> list of str

    Given an image dictionary return a list of the filenames
    sorted by date. 

    >>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], \
    'image2.jpg': ['UTSC', '2017-11-04', 'Happy Sat.']}
    >>> sorted_images(d)    
    ['image1.jpg', 'image2.jpg']
    '''
    return [k for k, v in sorted(image_dict.items(), key=lambda x: x[1][1])] 

首先,它是
,而不是
itmes
。。无论如何,
value\u dict
似乎是一个
列表,而不是一个
dict
好的,我如何将最终结果生成一个列表并按日期对图像进行排序?因为
image\u dict
是一个dict,所以键是唯一的。在这种情况下,您只需要
new\u list=image\u dict.keys()
Ok,我应该把它放在哪里?现在它说太多变量无法解压Ok,那么我如何修复这个
new\u list=[k代表image\u dict中的k]
可能?我不知道你想做什么。我只想让我的代码与docstring匹配,并使其适用于docstring中的示例。