Sep-08-2021, 07:31 PM
(This post was last modified: Sep-08-2021, 07:46 PM by deanhystad.)
I'm not sure I understand the question. Does this work for you?
Another possibility is that instead of mapping movie titles to a rating, you map the movie title to a list of ratings. If you have multiple ratings for the same movie you just append the rating to the list of ratings. I did something like that recently responding to a post about poker hands. I wanted to group cards by suit and by rank, so I subclassed dictionary to create keyed groups (lists).
mydict['Rocky 3'] = -1I am confused about "overwriting". Do you mean that you don't want to add a movie if it already exists in the dictionary, or do you mean you want to add the movie without it replacing the existing dictionary entry for that same movie? If the latter, that is not what dictionaries are for and you would be better off making a list of tuples (or named tuples).
Another possibility is that instead of mapping movie titles to a rating, you map the movie title to a list of ratings. If you have multiple ratings for the same movie you just append the rating to the list of ratings. I did something like that recently responding to a post about poker hands. I wanted to group cards by suit and by rank, so I subclassed dictionary to create keyed groups (lists).
class Grouper(dict): '''I am like a dictionary, but I can map multiple values to the same key''' def __init__(self, items=[]): super().__init__() for item in items: self[item[0]] = item[1] def __setitem__(self, key, value): group = self.get(key, []) group.append(value) super().__setitem__(key, group) def most_common(self): '''Return items sorted in decreasing order by count''' items = list(super().items()) items.sort(key=lambda item: len(item[1]), reverse=True) return items movies = Grouper((('Rocky', 5), ('Rocky II', 4), ('Rocky', 3))movies['Rocky'] would return a list of ratings for the movie: [5, 3]