Dictionaries Debugging#

Section Title: 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.