Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the expected output of the following Python code?

print("\nDictionary Iteration")
d = dict()
d['lmn'] = 123
d['abc'] = 345
for i in d :
    print("%s %d" %(i, d[i]))

  • A.Dictionary Iteration / lmn 123 / abc 345
  • B.Dictionary Iteration' / 123 lmn / abc 345
  • C.Dictionary Iteration' / 123 lmn / 345 abc
  • D.Dictionary Iteration' / lmn 345 / abc 123

Answer: A

The output is a blank line, then 'Dictionary Iteration', then 'lmn 123' and 'abc 345'. The string begins with \n, which prints an empty line first. The dictionary d keeps the keys in the order inserted (in current Python versions), so the loop for i in d goes over 'lmn' and then 'abc', and each pass prints the key with %s and its value with %d. So the lines are 'lmn 123' and 'abc 345'. The other options swap the key and the value or print wrong values, and they also have a stray quote mark in the title line.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.