1

Imagine that I have this list:

a=[ {'name':'John','number':'123'} , {'name':'Mike','number':'12345'} ,{'name':'Peter','number':'12'}]
name=input('insert your name')
number=input('insert your number')

If I want to have 3 scenarios: one where the name and number matches, the second where the name is correct but the number is incorrect and the last one where the name does not exist.

if {'name':name,'number':number} in a:
 print('okay')
else:
 if {'name':name} in a and {'number':number} not in a:
 print('user okay, but incorrect pass')
 else:
 print('No username')

This type of code will not work, right? So how can I solve the second step (after the first else)?

asked Mar 5, 2019 at 1:41

2 Answers 2

2

You could use any like so:

if {'name':name,'number':number} in a:
 print('okay')
elif any(entry["name"] == name for entry in a):
 print('user okay, but incorrect pass')
else:
 print('No username')

I also simplified your else: if: to use elif: instead.

answered Mar 5, 2019 at 1:50
Sign up to request clarification or add additional context in comments.

Comments

1

I would actually write the code like this, making use of list comprehension. It seems more readable.

if name in [pos['name'] for pos in a]:
 if number == [dd for dd in a if dd['name'] == name][0]['number']:
 print('okay')
 else:
 print('user okay but incorrect pass')
else:
 print('No username')

Or alternatively, if you are ok with a for loop:

for dd in a:
 if name == dd['name']:
 if number == dd['number']:
 print('okay')
 else:
 print('user okay but incorrect pass')
 break
else:
 print('No username')

Note the else after the for loop: this construct it's explained here.

The latter is more efficient, as it iterates over the list only once (and not all the list if a match is found).

answered Mar 5, 2019 at 2:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.