[英]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.