Issue
I am writing a program which asks the user for their name and email and stores it in a dictionary.
Name = the key. Email = the value.
I got that part down, the problem I have now is that I do not want to allow them to enter and store and email (value) that already exists in the dictionary. I cannot seem to stop that from happening. My program keeps allowing the user to write down and store an email that already exists.
My code:
users = {}
def option_2():
"""Function that adds a new name and email address"""
# Prompt user to enter both name and email address
name = input("Enter name: ")
email = input("Enter email address: ")
if email != users:
users[name] = email
print(users)
elif email in users:
print("That email is already taken.")
The result I keep getting is that it will store the duplicate emails when the name (the key) is different. I want the program to prevent them from doing it.
So for example,
{'Jeff': '[email protected]', 'Mark': '[email protected]}
Solution
You would need to do this:
if email in users.values():
print("That email is already taken.")
else:
users[name] = email
print(users)
What that does is checks if the email is already in the dictionary under any key, and if so, tells the user so. Otherwise, it sets the email in the dictionary.
Answered By - 2pichar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.