If you need a dictionary with different values ββinstead of a constant value, you can create it as shown below using a random module:
>>> import random >>> alphabet = 'abcdefghijklmnopqrstuvwxyz' >>> my_dict = dict([ (ch, random.randint(1,len(alphabet)) ) for ch in alphabet ] ) >>> my_dict {'a': 17, 'b': 15, 'c': 3, 'd': 5, 'e': 5, 'f': 13, 'g': 7, 'h': 1, 'i': 3, 'j': 12, 'k': 11, 'l': 7, 'm': 8, 'n': 23, 'o': 15, 'p': 7, 'q': 9, 'r': 19, 's': 17, 't': 22, 'u': 20, 'v': 24, 'w': 26, 'x': 14, 'y': 7, 'z': 24} >>>
I create dictionaries as above when I need a dictionary with random values ββfor testing purposes.
Another way to create a dictionary with each character is text with a number of characters.
>>> char_count = lambda text, char: text.count(char) >>> text = "Genesis 1 - 1 In the beginning God created the heavens and the earth. 2 Now the earth was formless and desolate, and there was darkness upon the surface of the watery deep, and God active force was moving about over the surface of the waters." >>> my_dict = dict( [ ( char, char_count(text, char) ) for char in text ] ) >>> my_dict {'G': 3, 'e': 32, 'n': 13, 's': 15, 'i': 5, ' ': 45, '1': 2, '-': 1, 'I': 1, 't': 17, 'h': 12, 'b': 2, 'g': 3, 'o': 12, 'd': 10, 'c': 5, 'r': 12, 'a': 19, 'v': 4, '.': 2, '2': 1, 'N': 1, 'w': 6, 'f': 6, 'm': 2, 'l': 2, ',': 2, 'k': 1, 'u': 4, 'p': 2, 'y': 1, "'": 1}
Explanation:
1. The lambda function counts the number of occurrences of a character.
2. Call the lambda function for each character in the text to get a counter for that specific character.
Note. You can improve this code to avoid repeated calls for repeated characters.
Using vocabulary understanding can be simpler than all of the above:
{ char:(text.count(char)) for char in text }