0

I'm currently learning Python as a student, but I can't seem to grasp the idea of dictionary.

Let's say

d = {'I': 1, ' ': 2, 'P': 1, 'L': 1, 'E': 3, 'H': 1, 'D': 1, 'N': 1}

I want to to use the function max to return the key which has the highest value.

max (d.values(), key = lambda x: x[0])

But I get an error which say

TypeError: 'int' object is not subscriptable
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
David Lie
  • 65
  • 2
  • 9
  • `d.values()` returns the dictionaries *values*, which are integers. You can't subscript those. – Andrew Li Nov 08 '16 at 12:48
  • You're indexing the integers. Checkout the duplicate for an appropriate way . – Mazdak Nov 08 '16 at 12:49
  • since d.values() returns a list, you can simply just get the maximum value of the list max(d.values()). You're currently trying to index an integer, which you can't do! – chatton Nov 08 '16 at 12:50
  • You can also use `[k for k in d.keys() if d[k] == max(d.values())][0]`. – barak manos Nov 08 '16 at 12:51

1 Answers1

0

You are asking max() to get the maximum value, because you passed in d.values(). Each of those values is an int object, so you can't do x[0] on those.

Pass in the dictionary itself, and as the key, use d.get. Iteration over that object produces keys, and max() will find the key based on what d.get(k) returns:

max(d, key=d.get)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343