-1

I'm getting this error when I try to do this function:

line 40, in <module> d[date].append(item)
builtins.AttributeError: 'str' object has no attribute 'append'

I heard that append does not work for dictionaries, how do I fix this so that my function runs?

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

Does anyone know how to fix this?

Kirby
  • 15,127
  • 10
  • 89
  • 104
cboost
  • 3
  • 6

1 Answers1

0

Your issue is not with the line where the error occurs, but on an earlier line when you first assign a value to d[date]. You want that value to be a list, but you're currently assigning a string.

I suggest changing this line:

d[date] = item

To:

d[date] = [item]

An alternative would be to use dict.setdefault instead of your if and else blocks. You can do d.setdefault(date, []).append(item) unconditionally and it will handle both new and existing dates correctly.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • Thanks! my output looks right now {'2014.11.03': ['images/skating.jpg', 'images/skating2.jpg'], '2013.02.03': ['images/sunglasses.jpg']} – cboost Nov 09 '17 at 17:52