[英]Another question: Phone dictionary problem 'while-loop' using Error
简单的问题制作电话词典
我想做的是把人的名字和号码放在字典里!
示例我想做什么
Enter command (a, f, d, or q).: a
Enter new name................: Perry
Enter new phone number........: 229-449-9683
Enter command (a, f, d, or q).: f
Enter name to look up...:
我想在输入时找到全名和号码
到目前为止我写的电话字典代码:
phone_dict = {}
command = input('Enter command (a, f, d, or q).: ')
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
while True:
if command == 'a':
newname
newphone
phone_dict[newname] = newphone
print(phone_dict)
# In here, 'while-loop' does not work.
在那里,如果我输入“a”命令,然后输入名称
字典应该是 { Perry: 229-449-9683}
谢谢,这个问题可能有点混乱,但如果你能帮助解决这个问题,我很高兴!
要使用该人的名字或姓氏查找号码,您可以:
a = 'Add a new phone number'
d = 'Delete a phone number'
f = 'Find a phone number'
q = 'Quit'
phone_dict = {}
while True:
# Gets the user command every loop
command = input('Enter command (a, f, d, or q).: ')
# Add a new registry to the directory
if command == 'a':
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
phone_dict[newname] = newphone
print(phone_dict)
# Find a registry on the directory
elif command == "f"
query = input("Enter name to look up...: ")
match = None
for key in phone_dict.keys():
if query.strip() in key:
match = phone_dict[key]
break
if match is None:
print(f"The name {query} could not be found on the directory")
else:
print(f"The phone number of {query} is {match}")
elif command == "d":
# Delete registry
elif command == "q":
# Quits program
else:
print(f"The command {command} was not found, please try again!")
在这种情况下,我使用query.strip()
删除任何可能导致找不到此人的额外开始/结束空格。
请让我知道这是否有帮助。 谢谢!
要从字典中查找结果,您可以遍历项目并检查键是否包含您要查找的字符串。 如果要获取满足查询的所有值,可以创建另一个列表或字典并存储找到的项目:
phone_dict = {
"Han Perry": "1234",
"Harry Gildong": "2345",
"Hanny Test": "123",
}
find_str = "Han"
result = {}
for key, value in phone_dict.items():
# Converting it to lower makes it case insensitive
if find_str.lower().strip() in key.lower():
result[key] = value
print(result)
# {'Han Perry': '1234', 'Hanny Test': '123'}
请注意,这将遍历字典的所有值: O(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.