-1

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!

Navidk
  • 612
  • 6
  • 14
  • Why would sorting strings be really inefficient? But given your format you can just use `Counter(sample).most_common(3)`. – jonrsharpe Jan 23 '20 at 13:27
  • I don't think this is duplicate as Author is looking for some solution without using inbuilt functions. Just using for loop and conditional statements – anuragal Jan 23 '20 at 14:12
  • Yes I would like to solve it without using inbuilt functions – Navidk Jan 23 '20 at 16:34

1 Answers1

0

You can use sorted function:

topn = 3

# ascending
dict(sorted(sample.items(), key=lambda x: x[0])[:topn])

{'item1': 45, 'item2': 35, 'item3': 41}

# descending
dict(sorted(sample.items(), key=lambda x: x[0], reverse=True)[:topn])
YOLO
  • 20,181
  • 5
  • 20
  • 40
  • If I had to solve this without using the 'lambda' function. Would it be able to iterate through them now that the key's are strings using only for loops and condition statements. – Navidk Jan 23 '20 at 13:35
  • you want to solve this using a for loop? – YOLO Jan 23 '20 at 13:56
  • Yes, I would like to solve this without using in-built functions – Navidk Jan 23 '20 at 16:33