wolfbagel
wolfbagel

Reputation: 478

How to Sum a list of dictionaries with the same key value pair?

I have this list of dictionaries:

[{Title: title1, Minutes: 657, Cat: Romance, Watched: Fully}, 
{Title: title2, Minutes: 128, Cat: Philosophy, Watched: Fully}, 
{Title: title3, Minutes: 76, Cat: Romance, Watched: Partially}]

I have to create a report of minutes watched for each Cat in it. If it's Fully watched then all the minutes get added, if it's partially watched then only half of the minutes get added, if it's unwatched then no minutes get added.

So an example output report would be:

Romance: 695
Philosophy: 128

I'm almost there, at least I think so. Here's my output:

{'Romance': 38, 'Philosophy':128}

It only seems to add Romance with the Partially and the total is not being updated.

Any help in the right direction would be great.

Here's my code:

def get_count(self, movie_list):
        final = {}
        for movie in self.movie_list:
            get_category = movie['Cat']
            minutes = int(movie['Minutes'])
            total = 0

            for key in movie:
                if movie[key] == get_category:

                    if movie['Watched'] == 'Fully':
                        total += minutes

                    elif book['Watched'] == 'Partially':
                        half_of_movie = minutes//2
                        total += half_of_movie
                    elif book['Watched'] == 'Unwatched':
                        total += 0

            final[get_category] = total


        print(final)

EDIT: Upon further review I think what's happening is I'm rewriting over the total.

In this line: for key in movie: I believe something is wrong. Perhaps it's just looping over all the keys and not getting the one I'd like.

Upvotes: 0

Views: 54

Answers (2)

Fish11
Fish11

Reputation: 463

Try this!

def get_count(self, movie_list):
        final = {}
        for movie in self.movie_list:
            cat = movie['Cat']
            final.setdefault(cat, 0)
            minutes = int(movie['Minutes'])

            if movie['Watched'] == 'Fully':
                final[cat] += minutes
            elif movie['Watched'] == 'Partially':
                final[cat] += minutes // 2

        print(final)

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195418

One possible version, using dict.setdefault() (doc):

data = [{'Title': 'title1', 'Minutes': 657, 'Cat': 'Romance', 'Watched': 'Fully'},
{'Title': 'title2', 'Minutes': 128, 'Cat': 'Philosophy', 'Watched': 'Fully'},
{'Title': 'title3', 'Minutes': 76, 'Cat': 'Romance', 'Watched': 'Partially'}]

out = {}
for item in data:
    out.setdefault(item['Cat'], 0)
    out[item['Cat']] += item['Minutes'] if item['Watched'] == 'Fully' else item['Minutes'] // 2

print(out)

Prints:

{'Romance': 695, 'Philosophy': 128}

Upvotes: 2

Related Questions