另一个问题:使用错误的电话词典问题“ while-loop”

问题描述 投票:0回答:2

弹出新问题!

因为你们都帮了我很多忙,所以我几乎完成了我的工作!

另一个问题在这里

一切正常,但是在命令'd'中,错误是'字典在迭代过程中改变了大小',我在这里错了吗?谢谢!

#a = 'Add a new phone number'
#d = 'Delete a phone number'
#f = 'Find a phone number'
#q = 'Quit'

phone_dict = {}


while True:

    command = input('Enter command (a, f, d, or q).: ')

    if command == 'a':

        newname = input('Enter new name................: ')
        newphone = input('Enter new phone number........: ')
        phone_dict[newname] = newphone

        print(phone_dict)

    elif command == 'f':

        findname = input('Enter name to look up...: ')
        for key in phone_dict.keys():

            if findname.strip() in key:

                print(key,'            ', phone_dict[key])

    elif command == 'd':

        removename = input('Enter name to delete...: ')
        for name in phone_dict.keys():

          if removename in name:

                del phone_dict[removename]


    elif command == 'q':
        print('>_')
        break

Thanks!
python dictionary while-loop split do-while
2个回答
0
投票

要从字典中查找结果,您可以遍历所有项目并检查键是否包含要查找的字符串。如果要获取满足查询条件的所有值,则可以创建另一个列表或字典并存储找到的项目:

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)


0
投票

使用您可能做的人的名字来查找电话号码:

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()删除可能导致找不到该人的任何多余的开始/结束空格。

请让我知道是否有帮助。谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.