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':
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?
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]