Nick Nick - 1 month ago 7
Python Question

Using Dictionaries to Count First Letter in a String - Python

I've been working on a dictionaries exercise in Python, and I'm fairly new to the language and programming in itself. I've been trying to take a string or list of strings and have my code compare the first letter of the strings and make a dictionary out of how many strings begin with a certain letter of the alphabet. This is what I have so far:

d = {}
text=["time","after","time"]
# count occurances of character
for w in text:

d[w] = text.count(w)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))


What I'm aiming for, is for example get the following result :

count_starts(["time","after","time"]) -->{'t': 2, 'a': 1}


But, what I'm getting is more like the following:

count_starts(["time","after","time"]) --> {time:2, after:1}


With what I have, I've been able to accomplish it counting how many times a whole unique string appears, just not the counting of JUST the first letter in the string.

I also tried the following:

d = {}
text=["time","after","time"]
# count occurances of character
for w in text:
for l in w[:1]:
d[l] = text.count(l)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))


but all that give me in the printed output is :

{"a":0,"t":0}


I'm using Python Visualizer for my testing purposes.

Answer
d = {}

text = ['time', 'after', 'time']

for w in text:
    if w:                         # If we have the empty string. w[0] Does not Exist (DNE)
        if w[0] in d:             # Check to see if we have first character in dictionary.
            d[w[0]] = d[w[0]] + 1 # Use the first character as key to dictionary.
        else:                     # If character has not been found start counting.
            d[w[0]] = 1           # Use the first character as key to dictionary.

Using Python's IDLE I get:

>>> d = {}
>>> text = ['time', 'after', 'time']
>>> for w in text:
    if w:
        if w[0] in d:
            d[w[0]] = d[w[0]] + 1
        else:
            d[w[0]] = 1

>>> print d
{'a': 1, 't': 2}
>>> 
Comments