I am taking a quiz and one of the questions asked what the output of the code included below would be:
dictionary = {
'one': 'two',
'three': 'one',
'two': 'three'
}
v = dictionary['one']
for k in range(len(dictionary)):
v = dictionary[v]
print(v)
I know that the answer is: two
But, I am unsure how we came up with that result.
I know that this line: v = dictionary[‘one’]
equals two but the for loop that follows it confuses me and im assuming that the answer to this question is two because the for loop didn’t change the original value of the first instance of v
Can someone explain to me what exactly is going on in this code?
I am having an issue understanding how this code is working?? I have been running it in debug and do not understand how it works?
This is what I know is that the very first v = dictionary[‘one’] just creates variable v, it gets an initial id and its type is a string.
then the for loop iterates over the dictionary keys (position 0,1,2) 3 times
v gets a new ID because it is created each time v = dictionary[v]
the answer is ‘two’ but I do not know how come??
Also, if I change the dictionary values to ‘2two’, ‘3three’, ‘2two’
I get a KeyError: ‘2two’
WHY? the dictionary value has nothing to do with the dictionary keys?
I have been working on this issue for a couple of days now and I am very frustrated I can not understand what is going on!
Any help anyone can give would be greatly appreciated, I do not have very much hair left!
ok, questions? why is the dictionary value being referred/look uped to a key? does the value hold the key? if so, why?
my understanding of dictionaries is that its value can be anything and does not have to refer to a key… is that correct?
for v = dictionary[‘one’] is the ‘one’ the dictionary key or value?
in my latest testing whatever the initial setting of v = dictionary[‘one’] or ‘two’ or ‘three’ the final value of dictionary(v) will be whatever you started with?
Thank you so much for your help!!! I desperately want to understand how this code works, not for a test question, but to know 100% myself what is going on! I have searched the internet for answers with little success!