-1
def max_n_min(dic):
dic_list = dic.items()[0]
max = min = dic_list
for value in dic.values():
    if value > max:
        max = value
    if value < min:
        min = value
return(max, min) 

 <ipython-input-16-5837f0a5d1aa> in max_n_min(dic)
  1 #Sums births for a requested periods
  2 def max_n_min(dic):    
----> 3     dic_list = dic.values()[0]
  4     max = min = dic_list
  5     for value in dic.values()    
TypeError: 'dict_values' object does not support indexing

I'm making a function that takes the values of the keys in a dictionary as input, and outputs the max and min of those values. All values and keys are integers. I want to set the default max and min as the value of the first key, but for some reason it's giving me the above TypeError. This is strange to me because in this thread, it seems to be the recommended solution.

Community
  • 1
  • 1
Tare Gaskin
  • 1,209
  • 2
  • 10
  • 13

2 Answers2

1

Because dict.values() returns a object of dict_values type. In order to make this work, you have to type-cast it to list (or tuple) as:

list(dic.values())[0]

Sample run:

>>> my_dict = {1: 2, 3: 4}

# Your syntax; raising error
>>> my_dict.values()[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_values' object does not support indexing

# type-casted to list; works fine
>>> list(my_dict.values())[1]
4
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Thank you very much for your prompt response. As this is my first post, i feel very enthusiastic about continuing to use stack overflow as a reference. – Tare Gaskin Jan 17 '17 at 20:24
  • 1
    This is **dangerous**: `dct.values()` is inherently **unordered**. Each time you call it you can get a different order. – TemporalWolf Jan 17 '17 at 20:31
  • That's true. I just helped you finding the issue you faced. In case you want to maintain the order, you definitely should not be using `dict.values()` of normal `dict`. However, you may prevent yourself from it via using `collections.OrderedDict` whose `dict.values()` returns the ordered response – Moinuddin Quadri Jan 17 '17 at 20:33
  • For the purposes of this program I actually prefer unordered to ordered. – Tare Gaskin Jan 28 '17 at 21:27
  • Dicts are no longer unordered in later pythons. Also, `tuple()` will use less memory if the dict is sizable. – Gringo Suave Dec 14 '22 at 22:19
0

You can do the same shorter using internals:

def max_n_min(dic):
    return (max(dic.values()), min(dic.values()))
Robin Koch
  • 716
  • 3
  • 12