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))
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))
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
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.