I am trying to get the top 3 values from a python dictionary. I wrote the following code where the key's are numbers and it works.
sample = {1 : 45, 2 :35, 3 : 41, 4 :55, 5: 24}
cnt=0
for key in sample.items():
cnt=cnt+1
for i in range (1,cnt):
for j in range(i+1,cnt):
if (sample[i]>sample[j]):
pass
elif(sample[i]<sample[j]):
temp=sample[i]
sample[i]=sample[j]
sample[j]=temp
j=0
for key,value in sample.items():
if(j<3):
print(key,value)
j=j+1
else:
break
How would I go ahead with this if the key's are strings, when the dictionary is
sample={'item1': 45, 'item2':35, 'item3': 41, 'item4':55, 'item5': 24}
I understand sorting each like this:
sample['item1']>sample['item2']
and so on would be really inefficient.
Thanks!