user1830692
user1830692

Reputation: 15

Group counted words in python

I list of words. I count them using:

cnt = Counter()
 for word in keywords:
  cnt[word] += 1
  cnt

After using this code my words look like:

android :3
windows :2
apple :5
samsung :2
motorola :2
iphone :3
nokia :5
alcatel :1

and now I would like to group it, result should look like below:

5 : apple
3 : android iphone
2 : windows samsung motorola
1 : alcatel

Upvotes: 1

Views: 96

Answers (1)

iruvar
iruvar

Reputation: 23394

You could use a defaultdict, with the default factory set to a list, then feed the Counter to it

from collections import defaultdict
d = defaultdict(list)
for key, value in cnt.items():
     d[value].append(key)     

for key, value in d.items():                                                
   print '{}:{}'.format(key, " ".join(value))                              

2:windows
3:android iphone
5:apple
....    

As an aside, you should be able to initialize the Counter directly, like so

cnt = Counter(keywords)

Upvotes: 1

Related Questions