![](/img/trans.png)
[英]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.