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]}
CodePudding user response:
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.
CodePudding user response:
You can check if a key already exists in a dictionary:
if key in mydict.keys():
print('key already exists!')
The same applies to values:
if value in mydict.values():
print("Value already exists!)
Applying this to your code:
def option_2():
name = input("Enter name: ")
email = input("Enter email address: ")
if name in users.keys():
print("User already exists!")
elif email in users.values():
print("Email already taken")
else:
users[name] = email
print(users)
CodePudding user response:
Depending on the number of emails you will be storing and on the frequency with which you will be accessing them, you may want to consider keeping them in a set:
users = {}
emails = set()
name = input("Enter name: ")
email = input("Enter email address: ")
if email not in emails:
users[name] = email
emails.add(email)
print(users)
else:
print("That email is already taken.")
CodePudding user response:
You'd have to iterate through the values and check if the email exists already.
There are two ways. If you want to make it fast O(1), you can create another dictionary simultaneously which takes email as keys and names as values.
d1 = {} #name as keys, email as values
d2 = {} #email as keys, name as values
# check the existence like this
if name in d1:
print('Name already exists')
elif email in d2:
print('Email already exists')
else:
d1[name] = email
d2[email] = name
The above code will take up double memory but it's faster. If you can't do that, just iterate through values and check like this:
But it's gonna be slower O(n) specially for long dicts:
if email in user.values():
print('Email already exists')