4

There is a way to find the key that denotes the highest value in a dictionary (in Python) as per this question. I would like to do it a bit differently though.

Imagine we have a dictionary D, say:

   D = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}

I would like to find the maximum value of the dictionary by looping over the values of the keys, each time comparing the values of two keys and then 'remember' the key that denotes highest value in a local variable. In the end, I should have found the key and its maximum value in D. In this case, we should have something like this:

compare('a', 'q') --> remember q
compare('q', 'b') --> remember b
compare('b', 'c') --> remember b

The maximum key is now 'b' with value 3.

But how do I compare the values of the keys in the for loop? How can I do something like:

for k,v in D.iteritems() : 
    if (dictitem) > (dictitem + 1) : 
        remember = dictitem 
    else : 
        remember = dictitem + 1 

But now something that actually works?

Community
  • 1
  • 1
Max Muller
  • 341
  • 1
  • 3
  • 10
  • See this [post](http://stackoverflow.com/a/16569584/1982962) and this [post](http://stackoverflow.com/a/268285/1982962) – Kobi K Dec 08 '13 at 13:03
  • @KobiK yes I have read these posts, but I would like to do it differently. I would like to loop through the dictionary and each time compare every two elements that are next to each other. – Max Muller Dec 08 '13 at 13:27
  • You are using an unordered dictionary. Theoretically the ordering could change arbitraly. – Don Question Dec 08 '13 at 14:08

6 Answers6

9
>>> D = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
>>> max(D, key=D.get)
'b'
henices
  • 249
  • 1
  • 7
  • Thanks, but I would like to do it differently. I would like to loop through the dictionary and each time compare every two elements that are next to each other. – Max Muller Dec 08 '13 at 13:27
2

@henices's answer is great, and you should use it. But to give you a general note on how to implement a max function:

D = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
my_max_val = 0
for k,v in D.items():
    if v > my_max_val:
        my_max_val=v
        my_max_key=k


>>> my_max_val
3
>>> my_max_key
'b'
zenpoy
  • 19,490
  • 9
  • 60
  • 87
  • What if there are 2 values of the same :O @zenpoy – School Nov 09 '18 at 06:32
  • @School - When comparing values it will return the correct answer, which is the largest value. The question is which key will it find. It will find the first key in the order of which the dictionary is ordered – zenpoy Nov 11 '18 at 08:21
  • so is it possible to print the same highest value and the different keys out? @zenpoy – School Nov 12 '18 at 01:08
  • 1
    @School - yes - instead of saving `my_max_val` you can save `my_max_val` and a `set` of `my_max_keys` and add a case for `v == my_max_val` – zenpoy Nov 12 '18 at 10:51
1

I think this could be another approach.You can use operator.itemgetter for that:

import operator
mydict = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
max(mydict.iteritems(), key=operator.itemgetter(1))[0]

And instead of building a new list in memory use stats.iteritems(). The key parameter to the max() function is a function that computes a key that is used to determine how to rank items.This will work for cases, where there are two max instread of one. Like in the case of

mydict = { 'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2 , 'd' : 7 , 'e' : 8 , 'd' : '4' }

The output in this case would be 'd'. As one of the values of d is max.

Hammad Haleem
  • 1,374
  • 1
  • 16
  • 26
0

It looks like you want fnd the maxium number in for loop ranther than use built-in function like max, i write code as follow, i hope it's useful to you.

  D= {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
  for index, k in enumerate(D.iterkeys()):
      if  not index:
         remember = k 
     else:
         if D[k] > D[remember]:
            remember = k 
  print remember
user2228392
  • 404
  • 2
  • 10
0

zenpoy's approach starts with a value that may not be a valid result. If the question had been to find the key with minimum value, the approach would fail. What you would want (aside from using max(D, key=D.get) approach) is

D = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
my_max_val = None
for k,v in D.items():
    if my_max_val is None:
        my_max_val=v
        my_max_key=k
    elif v > my_max_val:
        my_max_val=v
        my_max_key=k
0

Since you want to do this in a for loop, you could try zenpoy's approach. But make sure to use better initialization for my_max_val like MattNewville has done.

Here is the method similar to the structure you have provided in your question. `

D = {'a' : 1 , 'q' : 2,  'b' : 3, 'c': 2}
li = D.keys()
j = len(li)
for i in range(0,j-1):
    if D[li[i]]>D[li[i+1]]:
        maxi = D[li[i]]
    else:
        maxi = D[li[i+1]]
aste123
  • 1,223
  • 4
  • 20
  • 40