Как добавить обработку исключений, чтобы проверить, является ли вводимое пользователем значение ключом в dict - PullRequest
0 голосов
/ 01 августа 2020

В моем коде я разрешаю пользователю вводить значение ключа словаря для редактирования. Я хотел бы сделать так, чтобы пользователь мог вводить только те значения c, чтобы dict не добавлялся. вот мой код. требуется обработка исключений при редактировании и значении переменных.

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)

пример вывода, который видит пользователь.

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

Ответы [ 2 ]

0 голосов
/ 01 августа 2020

Я полагаю, вы хотите, чтобы программа вызвала исключение. Вы можете сделать это довольно просто.

...
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
...

Если вы не хотите создавать исключение, вы можете сделать что-то вроде этого.

...
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
...

Этот код запросит новый ввод от пользователя до тех пор, пока ввод не станет действительным.

0 голосов
/ 01 августа 2020

Я хотел бы ответить на ваш вопрос: D

Вот его код:

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>"

теперь вы можете использовать либо «метод повышения», либо вы можете используйте также метод 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)    

Надеюсь, это был удовлетворительный ответ: D

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...