我正在尝试验证用户的出生日期,并将其与字典数据库中存储的值进行比较。但是,即使我输入了正确的出生日期值,也无法验证该值。这是我的代码:
from collections import defaultdict
accountDetails = [
{"FirtsName": "JOHN", "LastName": "DENIS","date of Birth": "01-06-1992", "Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "AKASH", "LastName": "MAHAJAN", "date of Birth": "04-02-1995","Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "AMAN", "LastName": "RANA","date of Birth": "11-04-1996", "Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "ANKUR", "LastName": "JAIN","date of Birth": "21-05-1990", "Account Number": "432524352345234", "Account Balance": "50000"},
]
d = defaultdict(lambda: defaultdict(dict))
for item in accountDetails:
d[item['FirtsName']][item['LastName']][item['date of Birth']] = item
# get valid first name
while True:
first_name_input = input('Enter First Name:\n').upper()
if first_name_input in d:
break
else:
print('Enter valid First Name')
# get valid last name
while True:
last_name_input = input('Enter Last Name:\n').upper()
if last_name_input in d[first_name_input]:
break
else:
print('Enter valid Last Name')
# get valid last name
while True:
dob_input = input('Enter dob:\n')
if dob_input in d[first_name_input]:
break
else:
print('Enter valid dob')
print(d[first_name_input][last_name_input])
用户已将值设置为-04-02-1995
答案 0 :(得分:3)
您需要对嵌套字典的 second 级别中的键进行测试:
while True:
dob_input = input('Enter dob:\n')
if dob_input in d[first_name_input][last_name_input]:
break
else:
print('Enter valid dob')
当您print
创建的嵌套字典的结构时,这一点变得很清楚:
print(d)
defaultdict(<function __main__.<lambda>>,
{'AKASH': defaultdict(dict,
{'MAHAJAN': {'04-02-1995': {'Account Balance': '50000',
'Account Number': '432524352345234',
'FirtsName': 'AKASH',
'LastName': 'MAHAJAN',
'date of Birth': '04-02-1995'}}}),
...
'JOHN': defaultdict(dict,
{'DENIS': {'01-06-1992': {'Account Balance': '50000',
'Account Number': '432524352345234',
'FirtsName': 'JOHN',
'LastName': 'DENIS',
'date of Birth': '01-06-1992'}}})})