How to create new dictionary from string?

I have a string: my_str = "abra cadabra" I need to create a new dictionary , the keys in the dictionary are the letters in my_str and the value should be the amount of every letter. For example:

my_str = "abra cadabra" output >> {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1} 

What i got is – {'a': 5, 'b': 5, 'r': 5, 'c': 5, 'd': 5}

Add Comment
2 Answer(s)

Try this:

my_str = "abra cadabra" my_set = set(my_str) my_set.discard(" ") my_dict = {} for key in my_set:     my_dict[key] = my_str.count(key) print(my_dict)  
Answered on July 16, 2020.
Add Comment

collections.Counter could be used for this.

Example:

from collections import Counter  my_str = "abra cadabra" my_str = my_str.replace(" ", "")  c = Counter(list(my_str))  print('{}\n{}\n{}'.format(c, c.keys(), c.values())) 

output:

Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}) dict_keys(['a', 'b', 'r', 'c', 'd']) dict_values([5, 2, 2, 1, 1]) 

You can iterate through the keys and values just like you would a normal dict.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.