Home > Blockchain >  returning the key with the highest value in a dictionary
returning the key with the highest value in a dictionary

Time:10-02

I tried to modify a code in my lectures which is:

[x for x in d.keys() if d[x] == max(d.values())] #It was in square-brackets which I'm not sure what it does
print(x)

I also tried it on a sample dict, which gave an error too so not sure what went wrong. Error message: print(x) NameError: name 'x' is not defined

So I tried to turn it into the code below because I have difficulty understanding the code when it's stuffed into a line, which produces the wrong output for the key containing the largest value:

result = []
for key in d.keys():
   if d[key] == max(d.values()):
      result.append(key)
print(result) 

PS, I know there's a simpler way using dict.get or even using pandas but I don't fully understand it so I'm avoiding it and staying with the basic coding method.

More edits: The list of the dictionary is below: the second code prints out "VIC" (largest value in 98) rather than "NSW" which largest value is 100

Actual code:

result = []
for key in humidity_for_states.keys():
   if humidity_for_states[key] == max(humidity_for_states.values()):
      result.append(key)
print(result) 

Dictionary I have:

{'NSW': [81.0, 82.0, 99.0, 100.0, 96.0, 63.0, 85.0, 100.0, 83.0, 50.0, 83.0, 100.0, 90.0, 75.0, 58.0, 100.0, 70.0, 67.0, 100.0, 63.0, 57.0, 45.0, 57.0, 56.0],
 'QLD': [65.0, 69.0, 64.0, 80.0, 68.0, 78.0, 60.0, 77.0, 99.0, 72.0, 64.0, 71.0, 61.0, 76.0, 64.0, 44.0, 91.0, 72.0, 64.0, 41.0, 67.0, 32.0, 40.0, 37.0, 64.0, 56.0, 36.0, 37.0, 71.0, 33.0],
 'VIC': [92.0, 97.0, 94.0, 93.0, 65.0, 79.0, 83.0, 98.0, 70.0, 64.0, 86.0, 84.0, 71.0, 58.0, 63.0, 70.0, 85.0, 82.0, 46.0, 65.0, 94.0, 88.0],
 'SA': [52.0, 52.0, 57.0, 53.0, 54.0, 84.0],
 'WA': [19.0, 89.0, 53.0, 40.0, 45.0],
 'NT': [69.0, 64.0, 70.0, 67.0]}

CodePudding user response:

You get VIC because you're comparing the lists their normal way, i.e., lexicographically. You want to compare them by their max value instead.

One efficient way to do that:

maxes = list(map(max, humidity_for_states.values()))
maxmax = max(maxes)
result = [key
          for key, maxval in zip(humidity_for_states, maxes)
          if maxval == maxmax]
print(result) 

Another:

result = []
for key, vals in humidity_for_states.items():
    maxval = max(vals)
    if not result or maxval > maxmax:
        maxmax = maxval
        result = [key]
    elif maxval == maxmax:
        result.append(key)
print(result) 

CodePudding user response:

You can reshape your dictionary into a list of tuples holding max_humidity, location pairs. Since humidity is the first value, the max of this list is your winner.

data = {'NSW': [81.0, 82.0, 99.0, 100.0, 96.0, 63.0, 85.0, 100.0, 83.0, 50.0, 83.0, 100.0, 90.0, 75.0, 58.0, 100.0, 70.0, 67.0, 100.0, 63.0, 57.0, 45.0, 57.0, 56.0],
 'QLD': [65.0, 69.0, 64.0, 80.0, 68.0, 78.0, 60.0, 77.0, 99.0, 72.0, 64.0, 71.0, 61.0, 76.0, 64.0, 44.0, 91.0, 72.0, 64.0, 41.0, 67.0, 32.0, 40.0, 37.0, 64.0, 56.0, 36.0, 37.0, 71.0, 33.0],
 'VIC': [92.0, 97.0, 94.0, 93.0, 65.0, 79.0, 83.0, 98.0, 70.0, 64.0, 86.0, 84.0, 71.0, 58.0, 63.0, 70.0, 85.0, 82.0, 46.0, 65.0, 94.0, 88.0],
 'SA': [52.0, 52.0, 57.0, 53.0, 54.0, 84.0],
 'WA': [19.0, 89.0, 53.0, 40.0, 45.0],
 'NT': [69.0, 64.0, 70.0, 67.0]}

highest = max((max(val), key) for  key,val in data.items())[1]
print(highest)

Mostly. If multiple locations have the same high humidity, the one later in the alphabet wins. You could get a list in the event of a tie using groupby, which creates subiterators for like-valued items.

import itertools

# sort humidity/location pairs then use first like-valued group to choose highest
sorted_humidity_pairs = sorted(((max(val), key) for  key,val in data.items()),
        reverse=True)
for _, group in itertools.groupby(sorted_humidity_pairs, key=lambda pair: pair[0]):
    highest_group = [pair[1] for pair in group]
    break
else:
    print("no data")
    exit()
print(highest_group)

And if you want only one answer with each location weighted equally, you can randomly choose one.

import random
highest = random.choice(highest_group)
print(highest)
  • Related