0

I got an assignment to write a code that creates a dictionary that every key is a letter and every value is the number of that letter in user_str. It needs to look like this:

magic_str = "abra cadabra"
count_chars(magic_str)
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}

And this is my code, I will love to have suggestions on how to upgrade it and why this is the best option, or if there is another option:

def count_chars(my_str):
    """The func take string from user_str and create a dictionary of any letter as key and 
        and the value is how many from this letter there is in user_str
    Args:
        my_str (str): the user_str
        my_dict (dict): the dictionary of letters and numbers
    """
    my_dict = {}
    for i  in my_str:
        if i in my_dict:
            my_dict[i] = my_dict[i] + 1
    return my_dict

def main():
    user_str = input()
    count_chars(user_str)

if __name__ == "__main__":
    main()
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51

1 Answers1

0

Here are 2 ways to do this -

Using collections.Counter

Read more here

from collections import Counter

dict(Counter(magic_str.replace(' ','')))
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}

Using dict comprehension with str.count()

If you don't want to use collections.Counter try this -

def count_chars(string):
    stripped = string.replace(' ','')
    return {i:stripped.count(i) for i in set(stripped)}

count_chars(magic_str)
{'b': 2, 'c': 1, 'r': 2, 'd': 1, 'a': 5}

This method requires you to first find all the unique characters in the string using set and then using str.count(character) to find the # of times it occurs in that string. This can be done in 1 iteration through the unique characters in a dict comprehension.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51