-2

My Code is:

medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
def g(k,d):
    return d[k]
ks = medals.keys()
top_three = sorted(ks,key=lambda x : g(x,medals),reverse = True)

Actual Result :

['United States','China','Russia','Germany','Japan','South Korea']

But want to that result

['United States','China','Russia']

How it's possible please help anyone.

vahdet
  • 6,357
  • 9
  • 51
  • 106
Mahendra Seervi
  • 15
  • 3
  • 12

3 Answers3

0
medals = {'Japan':41, 'Russia':56, 'South Korea':21, 'United States':121, 'Germany':42, 'China':70}
def g(k,d):
    return d[k]
ks = medals.keys()
top_three = sorted(ks,key=lambda x : g(x,medals),reverse = True)[:3]
Ardein_
  • 166
  • 6
0

Just add the delimiter of three items only to your sorted results:

top_three = sorted(ks,key=lambda x : g(x,medals),reverse = True)[:3]
Tobias S
  • 1,275
  • 8
  • 23
0
required = list(dict(sorted(medals.items(), key = lambda x: x[1],reverse= True)).keys())[:3]

other_approach =list(map(lambda x: x[0],sorted(medals.items(), key = lambda x: x[1],reverse= True)))[:3]
Akhilesh_IN
  • 1,217
  • 1
  • 13
  • 19