Hello,
I am learning dictionaries and I need help. Here is a script and the task is to modify print_hist to print the keys and their values in alphabetical order.
I imagine that the result should be like this:
d 2
o 1
r 1
v 1
thing is I don't know how to do it the most simple way. Dictionary doesn't allow to sort the keys or values so in that case I need to transfer it to the list. Is it correct to do it this way?
def print_hist(h):
h=histogram(h)
k=h.keys()
k.sort()
for j in k:
print j, h[j]
print_hist('dodrv')
def histogram(h):
d = dict()
for c in h:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d # {'r': 1, 'd': 2, 'o': 1, 'v': 1}
histogram('dodrv')