0

I have a list of lists:

list1 =  [['This','could','be','heaven'] ,['This','could','be','hell'],['heaven','or','hell','i','like','it']]

I want to produce an ordered dictionary of word frequency where the word is the key and the value is the number of times it occurred in the entire list e.g.:

{'could': 2, 'hell':2, 'this':2,'be':2,'heaven':2,'like':1,'i':1,'it':1,'or':1}

I think I should be using set() + count() + dictionary comprehension; something like this:

res = {idx : list1[idx] for idx in set(list1)} 

print(res)

I know I should be able to do it one line but I need some help

Nikos M.
  • 8,033
  • 4
  • 36
  • 43

1 Answers1

4

If you want a one liner:

from collections import Counter
counts = Counter(x for sublist in list1 for x in sublist)

or a multi-liner without any imports:

counts = {}
for sublist in list1:
    for x in sublist:
        if x in counts:
            counts[x] += 1
        else:
            counts[x] = 0

though I recommend using Counter for readability.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35