简体   繁体   中英

Trying to get specific values from nested dictionary based on user input

I'm trying to get specific values from a nested dictionary based on user input. The code I have so far returns 'None None.' Any help would be greatly appreciated!

customer_dict = {
    "ctmr1" : {
        "Fname" : "John",
        "Lname" : "Smith",
        "Username" : "smithj",
        "Password" : "123"
    },
    "ctmr2" : {
        "Fname" : "Anita",
        "Lname" : "Job",
        "Username" : "joba",
        "Password" : "456"
    }
}

usrnm = input("Enter username: ")
psw = input("Enter password: ")

u = customer_dict.get("Username",{}).get(usrnm)
p = customer_dict.get("Password", {}).get(psw)

print (u,p)

if usrnm != u or psw != p:
    print("Wrong credentials")
else:
    print("Welcome!")

You are trying to get dictionary by username in first level, but username in the nested dict you need to get the nested dict first,

try a function like this, to get the user dict first

def get_user(users,username):
    for user in users.values():
        if user['Username'] == username:
            return user

then you could

uer = get_user(customer_dict,usrnm)

but i suggest rearrangin the dict, so as to have username as the key like

customer_dict = {
    "smithj" : {
        "Fname" : "John",
        "Lname" : "Smith",
        "Password" : "123"
    },
    ...
}

so instead of all this you could just do

customer_dict.get('username')

This will solve your problem

usrnm = input("Enter username: ")
psw = input("Enter password: ")

found_flag = False
for ctmr in customer_dict:
  u = customer_dict[ctmr].get("Username")
  p = customer_dict[ctmr].get("Password")
  if usrnm != u or psw != p:
    continue
  else:
    found_flag = True
    break

if found_flag == True:
  print('Welcome')
else:
  print('Wrong Credentials')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM