Home > Software engineering >  Combining dictionaries with same key while running in a loop?
Combining dictionaries with same key while running in a loop?

Time:03-01

I have a function that generates the frequency of the words in a sentence. I also have a list of sentences.

sentences = ["this word is used for testing", "code runs this word", "testing the code now"]

def findFreq():
    # create new dict
    # word freq finding code
    # print dict


for sen in sentences:
    findFreq(sen)

This gives me a result like:

{'this': 1, 'word': 1, 'is': 1, 'used': 1, 'for': 1, 'testing': 1}
{'code': 1, 'runs': 1, 'this': 1, 'word': 1}
{'testing': 1, 'the': 1, 'code': 1, 'now': 1}

But I want a result like this:

{'this': 2, 'word': 2, 'is': 1, 'used': 1, 'for': 1, 'testing': 2, 'code': 2, 'runs': 1, 'the': 1, 'now': 1}

I've seen solutions that use Counter and dictionary comprehension with Set, but How do I do combine them together while running in a loop like given above?

CodePudding user response:

If you want to keep your existing code, let findFreq return a dict (instead of printing it). Then update a Counter in each iteration of the for loop.

from collections import Counter

c = Counter()
for sen in sentences:
    c.update(findFreq(sen))

print(c)

If you want a shorter solution just use

>>> Counter(' '.join(sentences).split())
Counter({'this': 2,
         'word': 2,
         'is': 1,
         'used': 1,
         'for': 1,
         'testing': 2,
         'code': 2,
         'runs': 1,
         'the': 1,
         'now': 1})
  • Related