Home > front end >  Python dictionary only iterating the last key:value entry
Python dictionary only iterating the last key:value entry

Time:01-13

vin_bag = {}

option = int(input("PLease enter your option: \n"))

while option != 0:
    if option == 1:
        artist = input("Enter artist: \n")
        song = input("Enter song: \n")
        vin_bag[artist] = song

        option = int(input("PLease enter your option: \n"))

    elif option == 2:
        lib_songs = str(len(vin_bag))
        print("There are "   lib_songs   " songs in your music library. \n")

        option = int(input("PLease enter your option: \n"))

    elif option == 3:
        for song in vin_bag:
            print(artist, vin_bag[artist])

            option = int(input("PLease enter your option: \n"))

Option 3 iterates only over the last key:value entry and not the entire dictionary, what could I be doing wrong?

CodePudding user response:

First, I think you want to move your option input outside the scope of the for loop. Secondly, to iterate through a dictionary use vin_bag.items()

elif option == 3:
    for pair in vin_bag.items():
        print(pair)

    option = int(input("PLease enter your option: \n"))

CodePudding user response:


elif option == 3:

            [print(artist, song) for artist, song in vin_bag]

            option = int(input("PLease enter your option: \n"))

  •  Tags:  
  • Related