Dictionaries Debugging#
Each of the following short code contains one or more bugs.
Please identify and correct these bugs.
Provide an explanation for your answer.
Question-1#
{'A'=1, 'B'=2, 'C'=3}
Solution
For dictionaries, =
should be replaced with :
to associate keys with values.
Question-2#
my_dict = {'A':70, 'B':90, 'C':75, 'D':80}
my_dict('C')
Solution
my_dict(‘C’) must be my_dict[‘C’].
Question-3#
my_dict = ['A':70, 'B':90, 'C':75, 'D':80]
my_dict['C']
Solution
To construct a dictionary in Python, curly braces {}
must be used instead of square brackets []
.
Question-4#
stock_dict = {'day-1':{'High': 70, 'Low':62, 'Close':65},
'day-2':{'High': 68, 'Low':60, 'Close':63},
'day-3':{'High': 71, 'Low':65, 'Close':67},
'day-4':{'High': 70, 'Low':62, 'Close':65},
'day-5':{'High': 73, 'Low':65, 'Close':70},
'day-6':{'High': 75, 'Low':69, 'Close':73}
}
for i in [1,3]:
print(stock_dict['day-'+i]['Low'])
Solution
The counter i takes integer values, so it cannot be directly concatenated with ‘day-’. To resolve this issue, use 'day-' + str(i)
instead.
Question-5#
grades = {'Tim':90, 'Amy':95, 'Jack':85, ['Bob', 'Mia']:80}
grades
Solution
The list [‘Bob’, ‘Mia’] cannot be used as a dictionary key because it is mutable.
Question-6#
dict(('Tim', 'Jack', 'Mia'))
Solution
The dict() function expects key-value pairs, typically provided as a sequence of 2-element tuples.
Question-7#
my_dict = {'A':70, 'B':90, 'C':75, 'D':80}
print(my_dict['E'])
Solution
‘E’ is not a key in my_dict.
Question-8#
grades = {'Tim':90, 'Amy':95, 'Jack':85, ('A', 'B'):80}
print(grades['A'])
Solution
‘A’ is not a key in grades dictionary. The tuple (‘A’, ‘B’) is a key.