0

I recently started to learn Python and my latest assignment is to find element with highest (or lowest) value inside a dictionary which looks like:

Vals = {'a':11, 'b':10, 'c':12, 'a1':12, 'b1':13, 'c1':10, 'd':9}

My code was:

Maxm = 0

for Idx in range (0, len (Vals) - 1):
    if Vals [Idx] > Vals [Idx + 1]:
        Maxm = Vals [Idx]
    elif Vals [Idx] < Vals [Idx + 1]:
        Maxm = Vals [Idx + 1]
    else:
        pass

Then I received a key error. I used something similar to find maximum (minimum) in lists or tuples. I thought it might work with some modification for dictionaries.

NOTE: I can't use Python's built-in functions to find maixmum or minimum. It's unacceptable for us, you know.

Corv Vette
  • 13
  • 2
  • @Martijn Pieters♦ Don't mark me quickly. I mentioned that I can't use built-in functions like the one in THAT question. I can't use max () or min (0 or whatever. – Corv Vette Dec 26 '15 at 10:56
  • Your method (comparing with the next value) only works if you have a *sorted* list of numbers. Dictionaries are not sorted; they are unordered. Nor do dictionaries have indices. Have you studied `dict` objects at all? Do you know how to loop over all keys, or all values, or both? – Martijn Pieters Dec 26 '15 at 10:58
  • @Martijn Pieters♦ Yes I studied dictionaries. I know that we access them by keys and values. But shouldn't we access indexes in this case? This is the only thing that crossed my mind after reading my text book. – Corv Vette Dec 26 '15 at 11:03
  • To determine the maximum, just examine every value. If the value you are examining is higher than the maximum *found so far*, you have determined the new maximum. If you started with `max_found = None` and just test each value with `if max_found is None or current_value > max_found: max_found = value` you'll always end up with the maximum value in any sequence. Including the values of a dictionary. No indices required. – Martijn Pieters Dec 26 '15 at 11:05
  • @Martijn Pieters♦ Please unmark my question. It is clearly not a duplicate. – Corv Vette Dec 26 '15 at 11:31
  • Yet http://stackoverflow.com/a/17217820 doesn't use the `max()` function. – Martijn Pieters Dec 26 '15 at 11:46

0 Answers0