我尝试执行此功能时收到此错误:
line 40, in <module> d[date].append(item) builtins.AttributeError: 'str' object has no attribute 'append'
我听说追加不适用于字典,我如何解决这个问题以便我的函数运行?
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
有谁知道如何解决这个问题?
答案 0 :(得分:0)
您的问题不在于发生错误的行,而是在您第一次将值分配给=IF(COUNTIFS(A:A,A2,B:B,"<>" &B2),"ID with multiple names","match")
时的早期行。您希望该值为列表,但您当前正在分配字符串。
我建议改变这一行:
d[date]
要:
d[date] = item
另一种方法是使用d[date] = [item]
代替dict.setdefault
和if
块。您可以无条件地执行else
,它将正确处理新日期和现有日期。