Home > Enterprise >  Appending new value to dictionary key gives AttributeError: 'int' object has no attribute
Appending new value to dictionary key gives AttributeError: 'int' object has no attribute

Time:06-13

I'm trying to map list into dictionary with enumerate() function but when I tried to append new value to key, value pair with append it gives AttributeError. As per my understanding I think integers does not accept append function but I'm not appending to an integer then why I'm getting such error. Here is my code:

schedule = {}

for day, movie in enumerate(movies):
  if movie not in schedule:
    schedule[movie] = day
  else:
    schedule[movie].append(day)
print(schedule)

Please let me know if anyone know how to deal with it.

CodePudding user response:

The append method is defined for lists, but you're never creating a list in your code. The value of schedule[movie] gets set to day, which is an integer. You can't append to that value later!

I suspect you want schedule to always have values that are lists. In that case, you need to do the initial assignment with a list that contains the first day, rather than the day value directly:

if movie not in schedule:
    schedule[movie] = [day]      # add brackets to make a list
else:
    schedule[movie].append(day)  # now this will work

CodePudding user response:

As @Blckknght already explained, you are trying to append to an integer which does not have an append method. For the task you are trying to do, the standard library provides the default dictionary in the collections module.

from collections import defaultdict
schedule = defaultdict(list)

for day, movie in enumerate(movies):
  schedule[movie].append(day)
print(schedule)

If you want to learn more about the default dictionary, I recommend to read https://realpython.com/python-defaultdict/.

  • Related