0

I am looking for a solution:

Input is a string like s = "Hello World!"
The function should return a dictionary like:
{'e': 1, 'H': 1, 'r': 1, 'o': 2, 'd': 1, ' ': 1, 'l': 3, 'W': 1}

i just got an inefficient solution with get:

def char_count_dict(count_string):
     letter_dict = {}
     for letter in count_string:
         letter_dict[letter] = letter_dict.get(letter, 0)+1
     return letter_dict

1 Answers1

0

You can use high-performance container datatypes like collections.Counter https://docs.python.org/2/library/collections.html#collections.Counter

from collections import Counter

def char_count_dict(count_string):
    return dict(Counter(count_string))
Maciej M
  • 786
  • 6
  • 17