I am trying to count letter occurances and print them. This is what i have so far:
def histogram(L):
d = {}
for x in L:
for letter in x:
d
is a dictionary, not a list. Loop over the keys:
for key in d:
print('{} | {}'.format(key, d[key]))
or you'll get KeyError
exceptions.
You may be interested in the collections.Counter() class; it's a counting dictionary:
from collections import Counter
def histogram(L):
d = Counter(letter for line in L for letter in x)
for letter in d:
print('{} | {}'.format(letter, d[letter]))
return d
Just for fun, lets simplify your code. You can use a set() on the initial string to get a list of the unique characters, then just use the count method of the list.
def histogram(L):
d = {letter:L.count(letter) for letter in set(L)}
for key in d:
print "{} | {}".format(key, d[key]}