python-3.xdictionaryif-statementkeyerrorkey-value-store

I want to get a key as input and a comparison of key value in if condition


It shows KeyError: ('Black in Black', 8.5)

album_rating={"Black in Black":8.5,"Believer":6,"SmackTac":7,"You":9}
a=(input("Enter the name:"))

For a in album_rating.items():
    if(album_rating[a]>8):
     print("This album is Amazing!")
    else:        
     print("Try a different album")
print("Welcome")

Solution

  • There a couple of things which need fixing here. Firstly you name your input variable a but then use that to loop over your dictionary.

    Secondly dict.items() returns a list of key value pairs e.g.

    [('Black in Black', 8.5), ('Believer', 6), ('SmackTac', 7), ('You', 9)]) so a will never be found in the dictionary because you are comparing a string to a list hence the KeyError.

    If you want to loop over the keys of a dictionary specifically then you should use dict.keys(). Alternatively you can use a try-except block to catch any KeyErrors.

    album_rating={"Black in Black":8.5,"Believer":6,"SmackTac":7,"You":9}
    a=input("Enter the name:")
    
    try:
        album = album_rating[a]
        if(album_rating[a]>8):
            print("This album is Amazing!")
        else:        
            print("Try a different album")
    except KeyError:
        print ("Album does not exist")
    

    OR

    album_rating={"Black in Black":8.5,"Believer":6,"SmackTac":7,"You":9}
    a=input("Enter the name:")
    
    if a in album_rating.keys():
        if(album_rating[a]>8):
            print("This album is Amazing!")
        else:        
            print("Try a different album")
    else:
        print ("try again")