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}
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)
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.