0

The code is this and the output is two but I can't figure out why that is the output.

def dictTest(d, aVal):
    for k in d:
        if d[k] == aVal:
            return k
    return None

lengths = {'one':3, 0:1, 'two':3}
print(dictTest(lengths, 3))
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • What exactly are you having difficulty understanding? Go through the code line by line and try and see what each bit does. – Daniel Roseman Nov 06 '16 at 22:20
  • 1
    Dictionaries do not hold order. Keep running the code over and over again, eventually you will get one, then you will get two, then you will get one again. Because dictionaries do not preserve order. This is why: http://stackoverflow.com/questions/15479928/why-is-the-order-in-dictionaries-and-sets-arbitrary – idjaw Nov 06 '16 at 22:22
  • When I go line by line, I see: if index 0 in the dictionary == 3 then return k – Matt Schumacher Nov 06 '16 at 22:23
  • This is a review question for an exam and in the idle it outputs two but on the exam a possible answer is one but not two – Matt Schumacher Nov 06 '16 at 22:24
  • I know that dictionaries don't hold order but in the exam situation, a possible answer choice is one, would it be wrong if I selected that as a choice – Matt Schumacher Nov 06 '16 at 22:25
  • 1
    @MattSchumacher If you know dictionaries don't hold order, then you should know that based on the logic you wrote and the data you are providing, you will never be guaranteed to get ONLY `one` and never be guaranteed to get ONLY `two`. But you are guaranteed to get `one` OR `two` – idjaw Nov 06 '16 at 22:27
  • I understand now. so it will only return one thing. and in the exam selecting one would be correct. thank you – Matt Schumacher Nov 06 '16 at 22:28

2 Answers2

0

Dictionaries have no sense of ordering, so if you're checking if a value is a particular number, there's no guarantee you'll get the key that you're expecting to find if you have duplicate values.

If you want to Guarantee that a dictionary will be ordered, you can use collections.OrderedDict: https://docs.python.org/3/library/collections.html#collections.OrderedDict

AbrahamB
  • 1,348
  • 8
  • 13
0

While inserting the elements into the dictionary, they are not ordered. If you run your code multiple times, it would give you a varied result of 'one' and 'two'.

If your intention was to get all the key's for that value, you can store them in a list and return them.

vidyasagarr7
  • 513
  • 2
  • 6
  • 12