Home > Enterprise >  why does my if statement function only assign my print message to the last key-value in my dictionar
why does my if statement function only assign my print message to the last key-value in my dictionar

Time:04-03

favorite_languges = {
"John": "Python",
"Aisha": "C",
"Newton": "maths",
"Budon": "C  ",
}

# for loop to print all keys

for name in favorite_languges.keys():
    print(name.title())

# for loop to print message to all users in the friends list

friends = ['Budon', 'Aisha']
if name in friends:
    language = favorite_languges[name].title()
    print(f'\t{name.title()}, i see you love {language}')

I am trying to print the message print(f'\\t{name.title()}, i see you love {language}') to users who are in the friends list and also in the dictionary but its only assigns it to the last key-value in the dictionary

I tried to run it each line at a time but i don't seem to get the way out. I've been practicing for only 3 months

CodePudding user response:

You are not using a for loop for your second loop. So you need to add it. And there is one more thing: You should check whether a name is in the dictionary or not, otherwise you will get a KeyError for an unknown name.

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C  ", }

for name in favorite_languges.keys():
    print(name.title())

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C  ", }

for name in favorite_languges.keys():
    print(name.title())


friends = ['Budon', 'Aisha']
for name in friends:
    if name in favorite_languges:
        language = favorite_languges[name].title()
        print(f'\t{name.title()}, i see you love {language}')
    else:
        print(f"No information about {name}")

Expected output:

John
Aisha
Newton
Budon
John
Aisha
Newton
Budon
    Budon, i see you love C  
    Aisha, i see you love C

CodePudding user response:

It's possible that you're only running the if statement after the for loop has passed which means it'll always be at the last point in the array, try it like this:

favorite_languges = { "John": "Python", "Aisha": "C", "Newton": "maths", "Budon": "C  "}
friends = ['Budon', 'Aisha']
for name in favorite_languges.keys():
    print(name.title())
    if name in friends:
        language = favorite_languges[name].title()
        print(f'\t{name.title()}, i see you love {language}')
  • Related