[英]Get specific the nested key/values based on a condition from python nested dictionary
[英]Trying to get specific values from nested dictionary based on user input
我正在尝试根据用户输入从嵌套字典中获取特定值。 到目前为止,我拥有的代码返回“无无”。 任何帮助将不胜感激!
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!")
您正在尝试通过第一级的用户名获取字典,但是嵌套字典中的用户名您需要先获取嵌套字典,
尝试这样的功能,首先获取用户字典
def get_user(users,username):
for user in users.values():
if user['Username'] == username:
return user
那么你可以
uer = get_user(customer_dict,usrnm)
但我建议重新排列字典,以便将用户名作为键
customer_dict = {
"smithj" : {
"Fname" : "John",
"Lname" : "Smith",
"Password" : "123"
},
...
}
所以你可以做的不是这一切
customer_dict.get('username')
这将解决您的问题
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.