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')

Recommended Answers

All 2 Replies

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')
commented: nice use of set to get unique characters once and only once in loop +1

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.