tgtrmr
tgtrmr

Reputation: 159

Summing values in Counter dictionary

I've got a dictionary, what shows how many words 'WOMAN' had spoken in a movie script. Now I want t add up the value of the dictionary so I get a total count of the words spoken by 'WOMAN'. Is there a way to achieve this?

'WOMAN': Counter({'Mia': 4,
                           'a': 4,
                           'the': 4,
                           'and': 3,
                           'is': 3,
                           'on': 3,
                           '--': 3,
                           'it': 2,
                           'Then': 2,
                           'STUDIO': 2,
                           'Cappuccino,': 1,                              
                           'from': 1,
                           'her.': 1,
                           'No,': 1,
                           'I': 1,
                           'insist.': 1,
                           'She': 1,
                           'pays.': 1,
                           'smiles': 1,
                           'at': 1,
                           'drops': 1,
                           'bill': 1,
                           'in': 1,
                           'tip': 1,
                           'jar.': 1,
                           'watches': 1,
                           'as': 1,
                           'Woman': 1,
                           'walks': 1,
                           'off,': 1,
                           'joined': 1,
                           'screen:': 1,
                           '4:07.': 1})})

Upvotes: 1

Views: 678

Answers (2)

jpp
jpp

Reputation: 164843

Assuming you have to split your string beforehand to extract words, you can count the number of words at an earlier stage:

from collections import Counter

x = 'this is a test string with this string repeated'

words_split = x.split()

count, c = len(words_split), Counter(words_split)

print(count)
# 9

print(c)
# Counter({'this': 2, 'string': 2, 'is': 1, 'a': 1, 'test': 1, 'with': 1, 'repeated': 1})

Upvotes: 1

moghya
moghya

Reputation: 864

From documentation here, you can use sum(Counter.values())

d = {'women':Counter()}    
sum(d['women'].values())

Upvotes: 1

Related Questions