Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to find the frequency of letters without the Counter.And the code will output a dictionary form of result. And what I have done so far is to make the program count the word frequencies but not the letter/character frequencies. If anyone could point out my mistakes in this code that would be wonderful. Thank you. It supposed to look like this:

{'a':2,'b':1,'c':1,'d':1,'z':1}

**but this is what I am actually getting:

{'abc':1,'az':1,'ed':1}

**my code is below

word_list=['abc','az','ed']
def count_letter_frequency(word_list):
  letter_frequency={}
  for word in word_list:
    keys=letter_frequency.keys()
    if word in keys:
        letter_frequency[word]+=1
    else:
        letter_frequency[word]=1
  return letter_frequency
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
250 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use collections.Counter

from collections import Counter

print Counter(''.join(word_list))
# Counter({'a': 2, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'z': 1})

Or count the elements yourself if you don't want to use Counter.

from collections import defaultdict

d = defaultdict(int)
for c in ''.join(word_list):
    d[c] += 1
print d
# defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'z': 1})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...