r/pythontips • u/rao_vishvajit • Oct 17 '24
Syntax What will be the output of this code?
Question: Guess the Output
Consider the following Python code snippet:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict['d'] = my_dict.get('b', 0) + my_dict.get('e', 0)
my_dict['e'] = my_dict.get('d', 0) + 5
print(my_dict)What will be the output of this code?
A) {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 7}
B) {'a': 1, 'b': 2, 'c': 3, 'd': 0, 'e': 5}
C) {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 2}
D) {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 12}Thanks
0
Upvotes
2
u/kuzmovych_y Oct 17 '24
Please do your own homework/exam.
As for the commenters, please read about the dictionary's get method.
0
u/nlcircle Oct 17 '24
Logically, one would expect an error in the second line as my_dict['e'] doesn't exist. Unless some error catching mechanism handles this by some 'default behaviour'. which replaces that call with a value to allow continuing the process/
-2
u/[deleted] Oct 17 '24
what does the get method do