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)?

alladin
  • 33
  • 3

2 Answers2

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.

Loocid
  • 6,112
  • 1
  • 24
  • 42
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).

Valentino
  • 7,291
  • 6
  • 18
  • 34