1
   dct = {1:'James', 2:'Alex', 3:'Thomas'}
   if dct == 'James':
       print('There is a James in the dictionary.')
   else:
       print("There is no James.")

I can't seem to figure out why this if-else statement isn't working, I know it's something small but I keep getting the wrong output. Anyone know why? Is it a problem with my dictionary? Thanks for the help!

1
  • {1:'James', 2:'Alex', 3:'Thomas'} is not the same thing as 'James'. Commented Nov 20, 2017 at 3:35

1 Answer 1

2

You need something like this:

dct = {1:'James', 2:'Alex', 3:'Thomas'}
if 'James' in dct.values():
    print('There is a James in the dictionary.')
else:
    print("There is no James.")
  1. You need the in operator to compare 'James'
  2. You need to somehow iterate over the value of your dict, so getting a list with .values() and using in as I said in 1. is the easiest and most concise way.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, exactly what I needed! I just started using dictionaries so I've been trying basic functions with them, learning all the uses of dictionaries is still a work in progress.
Don't worry we have all been there! keep it up, we all need to improve. glad I could help! Just to be sure though, do you understand the mechanic behind my answer? Don't hesitate if you have any question.
@BlakeMcLaughlin Keep in mind that if you're going to be doing in checks on the values, those values should be keys instead, or else you defeat the purpose of dictionaries, which are efficient constant time lookups.
@cᴏʟᴅsᴘᴇᴇᴅ If I understand correctly, I totally agree with you. He could use a list if he does not need dictionary structure. But if not this is how I would implement it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.