Thursday , September 19 2024

What is the output of the following snippet? dct = {‘one’: ‘two’, ‘three’: ‘one’, ‘two’: ‘three’} v = dct[‘three’] for k in range(len(dct)): v = dct[v] print(v)

Questions BankCategory: Python Essentials 1What is the output of the following snippet? dct = {‘one’: ‘two’, ‘three’: ‘one’, ‘two’: ‘three’} v = dct[‘three’] for k in range(len(dct)): v = dct[v] print(v)
What is the output of the following snippet?

dct = {'one': 'two', 'three': 'one', 'two': 'three'}
v = dct['three']
 
for k in range(len(dct)):
    v = dct[v]
 
print(v)
  • (‘one’, ‘two’, ‘three’)
  • one
  • two
  • three

Explanation: Let’s analyze the code:

  • Line 1: the dct dictionary containing three key:value pairs is created
  • Line 2: the v variable is created and assigned the dictionary value associated with the ‘three’ key, that is the string “one”
  • Lines 4-5: the for loop performs three iterations (the length of the dct ctionary is 3):
  • after k = 0 v = “two”
  • after k = 1 v = “three”
  • after k = 2 v = “one”
  • the string “one” assigned to the v variable is then printed to the screen.

More Questions: Python Essentials 1 (PE1) Course Final Test