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

How to Prevent User from Inputting Existing Values in a Dictionary in Python

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.

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

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’: ‘jeff@gmail.com’, ‘Mark’: ‘jeff@gmail.com}

>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.

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