PrimingRyan
PrimingRyan

Reputation: 141

Total of each element in dictionary by python

I have data file like this:

{'one', 'four', 'two', 'eight'}
{'two', 'three', 'seven', 'eight'}

I want to get total of element and count each element. The result like this:

total of element: 8
one: 1, two: 2, eight: 2, seven: 1, three: 1, four: 1

Here is my code:

with open("data.json") as f:
     for line in f:
         result = json.loads(line)
         if 'text' in result.keys():
             response = result['text'] 
             words = response.encode("utf-8").split()
        list={}
        for word in words:

After this, I don't know how to get total of element and count each element. could you help me?

Upvotes: 0

Views: 113

Answers (1)

unutbu
unutbu

Reputation: 879701

You could use a collections.Counter:

import collections

counter = collections.Counter()

with open("data.json") as f:
    for line in f:
        result = json.loads(line)
        if 'text' in result.keys():
            response = result['text']
            words = response.encode("utf-8").split()
            counter.update(words)
print(counter)

Upvotes: 7

Related Questions