Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using for loop in python dictionary to print personal message to friends but it shows keyerror?

I am trying to loop through a dictionary, Which contains "friends name" and their favorite language:

favourate_language = {
    'yousuf': 'python',
    'jazam': 'C',
    'abu talib': 'C++',
    'abu hurayrah': 'Go',
    'umer': 'R',
    'kasim': 'javascript'
    }

After that I am trying to loop through this dictionary so that when a specific name comes then a personal message will be printed for that friend:

for name in favourate_language.keys():
    print(name)

# Displays personal message.
friends = ['yousuf', 'umer']

for name in favourate_language.keys():
    print(name.title())
    
    if name in friends:
        print('Assalamalaikum, ' + 
        name.title() + 
        "I see your favourate language is " + 
        favourate_language[name.title()] + "!")

But it shows me a keyerror for the word ‘yousuf’:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yousuf
Traceback (most recent call last):
  File "F:\Farhan anwar\python\users.py", line 40, in <module>
    favourate_language[name.title()] + "!")
    ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
KeyError: 'Yousuf'

I tried to check if the name was mispelled or capitalization mistake with the name ‘yousuf’, but it still shows the same error.

What I expected for the result was:

Yousuf
Muhammed
Assalamalaikum! Muhammed, I see your favourate language is C!
Abu Hurayrah
Ali
Assalamalaikum! Ali, I see your favourate language is Javascript!

But I failed to get the desired result, If you can solve this small problem?

>Solution :

favourate_language = {
'abc': 'python',
'xyz': 'C',
'abc xyz': 'C++',
'pqr mnq': 'Go',
'edc': 'R',
}
# Displays personal message.
friends = ['abc', 'edc']
for name in favourate_language.keys():
    print(name.title())
    if name in friends:
        print('Good Morning, ' + 
        name.title() + 
        "I see your favourate language is " + 
        favourate_language[name] + "!")

names are key in dictionary.
Do not use the method title() on key, it return string in title format.

favourate_language[name]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading