简体   繁体   English

如何添加异常处理以检查用户输入值是否是字典中的键

[英]How to add exception handling to check if a user input value is a key in a dict

In my code, i allow the user to enter the key value of the dictionary for them to edit.在我的代码中,我允许用户输入字典的键值供他们编辑。 I would like to make It so the user can only enter those specific values so the dict doesnt get added to.我想做它,所以用户只能输入那些特定的值,这样字典就不会被添加到。 here is my code.这是我的代码。 need exception handling on variables edit and value.需要对变量编辑和值进行异常处理。

def edit_items(info):
xy = info
while True:
    print('Index |       Orders')
    for x in range(len(xy)):
        print(x,xy[x])

    choice = int(input('Which entry would you like to edit?\nChoose by index: '))
    print(xy[choice])
    edit = input('What you want to edit: ')   # Key val of dict 
    value = input("Enter: ")    # Value for the specific key in dict
    xy[choice][edit.capitalize()] = value
    print('list updated.')
    print(xy[choice])
    with open('cart.txt','w') as file:
        file.write(str(xy))
    file.close()

    more_edits = input('\nDo you want to make more edits?(y/n): ')
    if more_edits == 'n':
        break
print(xy)

example of output the user sees.用户看到的 output 示例。

0 {'Item': 'edd', 'Price': '1.0', 'Quantity': '1'}
1 {'Item': 'milk', 'Price': '1.0', 'Quantity': '1'}

I'd love to answer your question:D我很乐意回答你的问题:D

Here's the code for it:这是它的代码:

def edit_items(info):
    #assuming that info is a dict
    someKey = input("Enter the key to edit the val:")
    if someKey not in info:
        raise "KeyNotFound: <Error Message>"

you're now to use either the 'raise method', or you can use 'try/except' method as well:您现在可以使用“raise 方法”,也可以使用“try/except”方法:

def edit_items(info):
    #assuming that info is a dict
    someKey = input("Enter the key to edit the val:")
    try:
        info[someKey] = input("Enter the value for the key:")
    except Exception as e:
        print(e)    

I hope this was a satisfactory answer:D我希望这是一个令人满意的答案:D

I expect you want the program to raise an exception.我希望您希望程序引发异常。 You can do this quite simply.你可以很简单地做到这一点。

...
edit = input('What you want to edit: ')   # Key val of dict 

if edit not in xy.keys():
    raise KeyError(f'There is no item called {edit}')  #raises a KeyError

value = input("Enter: ")    # Value for the specific key in dict

xy[choice][edit.capitalize()] = value
...

If you don't want to raise an exception you could do something like this.如果你不想引发异常,你可以做这样的事情。

...
edit = input('What you want to edit: ')

while edit not in xy.keys():
    print('You can\'t edit that')
    edit = input('What you want to edit: ')

value = input("Enter: ")    # Value for the specific key in dict

xy[choice][edit.capitalize()] = value
...

This code will ask for a new input from the user until the input is valid.此代码将要求用户提供新的输入,直到输入有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM