0

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')
3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by woooee
2

You could try this :

def histogram(string):
	hist = dict()
	for char in set(string) :
		hist[char] = string.count(char)
	return hist

def print_hist(h):
	hist = histogram(h)
	for key in sorted(hist.keys()) :
		print '%s : %d' % (key, hist[key])

print histogram('this is a test string')
print_hist('this is a test string')
Votes + Comments
nice use of set to get unique characters once and only once in loop
0

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?

That is the way that it is usually done. In fact I can't think of any other way to order keys in an existing dictionary. Note that you are re-using the same variable here
h=histogram(h)
In this case it doesn't matter but it is not a good habit to form. Also, when you start debugging code you will learn the importance of descriptive variable names.

Edited by woooee: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.