1

I am trying to find the most positive and most negative values in the dictionary imdb_dict:

imdb_dict = {'the': '0.0490972013402',
 'and': '0.201363575849',
 'a': '0.0333946807184',
 'of': '0.099837669572',
 'to': '-0.0790210365788',
 'is': '0.188660139871',
 'it': '0.00712569582356',
 'in': '0.109215821589',
 'i': '-0.154986397986'}

Using the code found here: Getting key with maximum value in dictionary?

I can obtain the maximum value of the dictionary using:

import operator
max(imdb_dict.items(), key=operator.itemgetter(1))

However, I cannot find a way to get the most negative value in the dictionary as using min shows the value closest to 0. Is there a way to modify the operator to get the maximum negative value or an easier way to accomplish the same?

notlaughing
  • 177
  • 2
  • 12

3 Answers3

6

The issue here is that the values are strings, so the ordering is lexicographical. You'd need a lambda function to take the min over the values in the dictionary as floats:

min(imdb_dict.items(), key=lambda x: float(x[1]))
# ('i', '-0.154986397986')

Note that by doing:

'-0.154986397986' < '-0.0790210365788'

You get False, as this is just checking what position a given character occupies in the ASCII table to discern which is the lowest. Hence the character that will decide which string is lowest will be where the first difference takes place, in this case the digit right after the dot, i.e 1 and 0.

yatu
  • 86,083
  • 12
  • 84
  • 139
0
imdb_dict = {'the': '0.0490972013402',
 'and': '0.201363575849',
 'a': '0.0333946807184',
 'of': '0.099837669572',
 'to': '-0.0790210365788',
 'is': '0.188660139871',
 'it': '0.00712569582356',
 'in': '0.109215821589',
 'i': '-0.154986397986'}

min_val = min(map(lambda x:float(x), imdb_dict.values()))
key = [i for i in imdb_dict.keys() if imdb_dict[i]==min_val]

print(key)
# output 'i'
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

Here

imdb_dict = {'the': '0.0490972013402',
             'and': '0.201363575849',
             'a': '0.0333946807184',
             'of': '0.099837669572',
             'to': '-0.0790210365788',
             'is': '0.188660139871',
             'it': '0.00712569582356',
             'in': '0.109215821589',
             'i': '-0.154986397986'}

for i, k in enumerate(imdb_dict.keys()):
    if i == 0:
        _min = (float(imdb_dict[k]), k)
    else:
        if float(imdb_dict[k]) < _min[0]:
            _min = (float(imdb_dict[k]), k)
print(_min)

output

(-0.154986397986, 'i')
balderman
  • 22,927
  • 7
  • 34
  • 52