-2
def character_frequency(string):
    for i in string:
        count = 0
        print(i,":", count, end = ", ")
        count += 1
    return count


print(character_frequency("dortmund"))

My goal is to print each letter and see how many times that letter exists in the string.

I tried print each letter and the use a variable called count to iterate over each letter and see how many times that letter exists in the string.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • 3
    https://docs.python.org/3/library/collections.html#collections.Counter – Klaus D. Feb 20 '23 at 00:18
  • `Counter()` is the best shortcut for sure. Instructionally, you might use a dictionary with each letter being the key to count up letter frequencies. If you do, `setdefault()` might help you as well – JonSG Feb 20 '23 at 00:38

1 Answers1

0

You can use collection.Counter class, from the documentation:

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Elements are counted from an iterable or initialized from another mapping (or counter):

c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args

Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError:

c = Counter(['eggs', 'ham'])
c['bacon']                              # count of a missing element is zero

Setting a count to zero does not remove an element from a counter. Use del to remove it entirely:

c['sausage'] = 0                        # counter entry with a zero count
del c['sausage']                        # del actually removes the entry

New in version 3.1.

Changed in version 3.7: As a dict subclass, Counter inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.


You can then just print the Counter object, use the pprint library, or write some pretty printing code yourself.

Caridorc
  • 6,222
  • 2
  • 31
  • 46