我正在从用户输入中获取一个值,并检查它是否存在于列表字典数据库中。我在字典项目中与之比较的值存储在列表中。但是,如果用户输入的值与数据库中存储的值匹配,我将无法执行任何操作。这是我的代码:
userDetails = []
# dateOfBith=['1992-09-01','1995-04-04','1993-04-06']
# datetimeparse = datetime.strptime(dateOfBith,'%dd-%mm-%yyyy')
# dateparse = datetime.datetime.strptime(dateOfBith, '%Y-%m-%d').strftime('%d-%m-%y')
accountDetails = [
{"FirtsName": "JOHN", "LastName": "DENIS", "Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "AKASH", "LastName": "MAHAJAN", "Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "AMAN", "LastName": "RANA", "Account Number": "432524352345234", "Account Balance": "50000"},
{"FirtsName": "ANKUR", "LastName": "JAIN", "Account Number": "432524352345234", "Account Balance": "50000"},
]
for x in accountDetails:
print (x["FirtsName"], x["LastName"], x["Account Number"], x["Account Number"])
specialCharacters = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
firstName = str(input("Enter First Name"))
FIRSTNAME = firstName.upper()
while FIRSTNAME == "" or FIRSTNAME.isdigit() or specialCharacters.search(FIRSTNAME) != None:
print("The account does not exist with the given details,Enter valid First name")
firstName = str(input("Enter First Name"))
FIRSTNAME = firstName.upper()
while FIRSTNAME:
for x in accountDetails:
usersFirstName = x["FirtsName"]
print(usersFirstName)
for j in usersFirstName:
FIRSTNAME != j:
print("The account does not exist with the given details,Enter valid First name")
firstName = str(input("Enter First Name"))
userDetails = firstName.upper()
else:
userDetails.append(FIRSTNAME)
lastName = str(input("Enter Last Name"))
答案 0 :(得分:0)
您的逻辑似乎过于复杂。我的建议是重组字典,可能使用collections.defaultdict
。然后只需查询您的新词典。这意味着您可以为每个查询利用O(1)查找的复杂性,而不是O(n)。
from collections import defaultdict
# restructure as nested dictionary
d = defaultdict(lambda: defaultdict(dict))
for item in accountDetails:
d[item['FirtsName']][item['LastName']] = 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')
print(d[first_name_input][last_name_input])
对于重复的名字和姓氏组合,您可以使用嵌套defaultdict
而不是list
的{{1}}值。
示例
dict
答案 1 :(得分:0)
def isDuplicate(value, fieldName, database):
for entry in database:
if fieldName in entry and entry[fieldName] == value:
return True
return False
此函数将检查输入是否以所需fieldName的形式存在于数据库列表中的任何条目中。一个检查JOHN是否以名字出现的例子是。
isDuplicate("JOHN", "FirstName", accountDetails)