Counting Letters Using a Python Dictionary
the Python version of arrays will suffice.
Dictionaries are not mentioned in the specifications at GCSE level, but they are such an integral part of Python that any serious student of the language should make a start on learning about them as early as possible. Certainly at A Level they will become very relevant, and will be studied as part of the topic of hashing algorithms.
To help you to gain some familiarity with this important topic, there is some code below that should serve as a basic introduction to Python dictionaries. If you want to get some experience working with this structure, type the code into your favourite editor and run it to see how it works. Then experiment with it and try some ideas of your own. Maybe you could make a small phone book, or an inventory of some kind.
Counting Letters Using a Python dictionary – Listing
def letter_freqs(a_string): freqs = {} for ch in a_string: if ch in freqs: freqs[ch] += 1 else: freqs[ch] = 1 return freqs # A test string my_string = "supercalifragilisticexpialidocious" # Get result result = letter_freqs(my_string) # Some ways of displaying the result print(result) print(result.keys()) print(result.values()) for (key, value) in letter_freqs(my_string).items(): print("Character", key, "count: ", value)
{'s': 3, 'u': 2, 'p': 2, 'e': 2, 'r': 2, 'c': 3, 'a': 3, 'l': 3, 'i': 7, 'f': 1, 'g': 1, 't': 1, 'x': 1, 'd': 1, 'o': 2} dict_keys(['s', 'u', 'p', 'e', 'r', 'c', 'a', 'l', 'i', 'f', 'g', 't', 'x', 'd', 'o']) dict_values([3, 2, 2, 2, 2, 3, 3, 3, 7, 1, 1, 1, 1, 1, 2]) Character s count: 3 Character u count: 2 Character p count: 2 Character e count: 2 Character r count: 2 Character c count: 3 Character a count: 3 Character l count: 3 Character i count: 7 Character f count: 1 Character g count: 1 Character t count: 1 Character x count: 1 Character d count: 1 Character o count: 2
The big concept here is the idea of key, value pairs. In some languages dictionaries are called associative arrays as they associate a value with a key. Whatever the name, these structures offer some powerful possibilities for a programmer and are certainly worth learning about.
Have fun, and please feel free to comment below.
Below are products related to this article, some of which may be affiliate links.