Problems with dictionary example
当我尝试执行此函数时,会收到此错误:
1
2 line 40, in <module> d[date].append(item)
builtins.AttributeError: 'str' object has no attribute 'append'
我听说append不适用于字典,如何修复这个问题以运行函数?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | def create_date_dict(image_dict): '''(dict of {str: list of str}) -> (dict of {str: list of str}) Given an image dictionary, return a new dictionary where the key is a date and the value is a list of filenames of images taken on that date. >>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday']} >>> date_d = create_date_dict(d) >>> date_d == {'2017-11-03': ['image1.jpg']} True ''' d = {} for item in image_dict: date = image_dict[item][1] filename = item if date not in d: d[date] = item elif date in d: d[date].append(item) return d |
有人知道怎么解决这个问题吗?
您的问题不在于错误发生的行,而在于您第一次将值赋给
我建议更改此行:
1 | d[date] = item |
到:
1 | d[date] = [item] |
另一种选择是使用