KeyError: 1, 2, 0, 8

https://app.dataquest.io/m/1020/dictionaries/1/invert-dictionary

Code:

def swap(dict_name1):
    dict_name2={}
    for key in dict_name1: 
        x=dict_name[key]
        y=key
        dict_name2[x ] =y
    return dict_name2

Error:

  • Executing the function swap caused an error: KeyError: 1.
  • Executing the function swap caused an error: KeyError: 2.
  • Executing the function swap caused an error: KeyError: 0.
  • Executing the function swap caused an error: KeyError: 8.

What is wrong with this code please.

Thank you!

1 Like

Hi @piya,

Please replace x=dict_name[key] with x=dict_name1[key] and your code will pass.

Best,
Sahil

1 Like