- Count how many of each alphabetic character.
Use a dictionary:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
e.g {"Key1" : "Value 1", 1 : 2, "Key3" : 4, 5 : "Value5"}
In this case, for counting, we could set up the dictionary to be like this:
{character : # of times it has shown up}
e.g {"a" : 7, "b" : 29}
How would we use a dictionary as a counter? Well, you see, they have this cool feature. If the Value
of a Key
is an int()
or float()
, you can use it like an int or float!
>>> example = {'letter' : 13}
>>> example['letter'] += 10
>>> example['letter']
23
>>> example['letter'] *= 1.02
>>> example['letter']
23.46
Knowing this, we could iterate through all the letters in a list or paragraph and either add them to the dictionary and set their value to 1 (if they have’t been added) OR, if they have been added, just += 1
to their value.
solved Not Sure How To Make A Counter [closed]