user3078517
user3078517

Reputation: 7

Updating dictionaries in python

Hello i am building a small project where a user can enter a new key and value into the dictionary. Is it possible to have a message displayed if the user enters a key or value that has already been entered into the dictionary telling them that they need to enter a new key or value as the one they have currently entered already exists?

This is some of the code i am currently using.

# dictionary with key:values.
reps = {'#':'A', '*':'M', '%':'N'}

### The users guess

print ("Now it's your turn to guess the rest of the letters!")

###Score
guesses = 0

### Update the dictionary with the users new guesses
while guesses < 10:
    symbol = input('Please enter the symbol: ')
    letter = input('Please enter the letter: ')
    reps[symbol] = letter

### Re printing the updated list
    for line in lines_words:
        txt = replace_all(line, reps)
        print (txt)
    guesses + 1

Upvotes: 0

Views: 59

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125268

You can test for existing keys and values with in:

if symbol in reps:
    print("You already defined that symbol")

For the letters, you'll have to test against all values in the dictionary:

if letter in reps.values():
    print("You already defined that letter")

You could combine the two:

if symbol in reps or letter in reps.values():
    print("You already used either the symbol or the letter")

Upvotes: 1

Related Questions