Reputation: 117
Im trying to split a string of letters into a dictionary which automatically adds the value +1 for every letter present more than once.
The only problem is that my code adds the value +1 for every key...For example if i input: "aasf" the dict will be: a:2, s:2, f:2... Whats wrong??
word = raw_input("Write letters: ")
chars = {}
for c in word:
chars[c] = c.count(c)
if c in chars:
chars[c] += 1
print chars
Upvotes: 2
Views: 536
Reputation: 59674
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
>>> from collections import Counter
>>> Counter('count letters in this sentence')
Counter({'e': 5, 't': 5, ' ': 4, 'n': 4, 's': 3, 'c': 2, 'i': 2, 'h': 1, 'l': 1, 'o': 1, 'r': 1, 'u': 1})
>>>
Upvotes: 3
Reputation: 13103
you must use either
chars[c] = words.count(c)
OR
chars[c] += 1
but not both.
Upvotes: 1