Tom Lehrte
Tom Lehrte

Reputation: 13

Selecting highest three values from a Python Dictionary

I am supposed to select the highest three values from a dictionary without sorting it or importing additional packages. So far I was only able to select the highest value.

print("enter a string s")
s = input()
frequency = {}

for i in s:
    if i in frequency:
        frequency[i] = frequency[i]+1
    elif i == ' ':
        pass
    else:
            frequency[i] = 1
a = max(frequency, key=frequency.get)

How could I select the other values ??

Upvotes: 0

Views: 72

Answers (3)

delica
delica

Reputation: 1707

You can find the highest value, remove it from the dictionary and then run your algorithm again on the dictionary.

Upvotes: 0

The_spider
The_spider

Reputation: 1255

I would like to note that your for loop can be written a bit simpler, like the following:

for i in s:
    if i in frequency:
        frequency[i] +=1
    elif i != ' ':
        frequency[i] = 1

You should never use if statements with pass in order for the else clause not to become executed, as you can always simplify them.

Upvotes: -1

Kapocsi
Kapocsi

Reputation: 1032

The constraints of your problem seem strange.

This is not the best way to solve this problem.

Nonetheless, remove the most frequent value from the dictionary and then repeat the procedure.

print("enter a string s")
s = input()
frequency = {}

for i in s:
    if i in frequency:
        frequency[i] = frequency[i]+1
    elif i == ' ':
        pass
    else:
        frequency[i] = 1
a = max(frequency, key=frequency.get)
del frequency[a]
b = max(frequency, key=frequency.get)
del frequency[b]
c = max(frequency, key=frequency.get)
del frequency[c]

Upvotes: 2

Related Questions