Computer Science

Predict the output of the following code:

d = {"apple": 15, "banana": 7, "cherry": 9} 
str1 = "" 
for key in d: 
    str1 = str1 + str(d[key]) + "@" + "\n"
str2 = str1[:-1] 
print(str2) 

Python

Python Dictionaries

4 Likes

Answer

15@
7@
9@

Working

  1. Initialization:
    • A dictionary d is created with three key-value pairs.
    • An empty string str1 is initialized.
  2. Iteration: The for loop iterates over each key in the dictionary:
    • For "apple": str1 becomes "15@\n" (value 15 followed by "@" and a newline).
    • For "banana": str1 becomes "15@\n7@\n" (adding value 7 followed by "@" and a newline).
    • For "cherry": str1 becomes "15@\n7@\n9@\n" (adding value 9 followed by "@" and a newline).
  3. The line str2 = str1[:-1] removes the last newline character from str1, resulting in str2 being "15@\n7@\n9@".
  4. Finally, print(str2) outputs the content of str2.

Answered By

1 Like


Related Questions