Проблема, возникающая при использовании словарей в python - PullRequest
1 голос
/ 13 июля 2020

Вот файл с именем dictionaries.py со следующим кодом:

commands={1:"GO", 2:"LOCKED", 3:"CLOSED", 4:"CHECKED"}

Вот еще один файл с именем main.py , который принимает ввод от пользователя и сохраняет его в переменной с именем введите . Теперь эта переменная содержит словарь для доступа из dictionaries.py , который был импортирован. Я написал следующий код, но он дает мне сообщение об ошибке -

selection = dictionaries.enter AttributeError: модуль 'dictionaries' не имеет атрибута 'enter'

import dictionaries

enter = input("enter your selection: ")
selection = dictionaries.enter
print(selection)

Ответы [ 3 ]

0 голосов
/ 13 июля 2020

Если ваша библиотека:

# ./dictionaries.py
commands = {1: "GO", 2: "LOCKED", 3: "CLOSED", 4: "CHECKED"}

Тогда ваше использование должно быть:

# ./main.py

import dictionaries

# Assume the user gives you valid input. In real life,
# you should write some error handling here
entry = input("enter your selection: ")

# entry is assumed to be something like `commands`
user_selected_dict = getattr(dictionaries, entry)

# this should work now
assert user_selected_dict[1] == "GO"
0 голосов
/ 13 июля 2020

Когда вы используете его как 'selection = dictionaries.enter' python будет искать 'enter' как атрибут, а не как значение, попробуйте это как 'selection = dictionaries [enter] », он должен работать следующим образом

0 голосов
/ 13 июля 2020

Вы используете неправильный синтаксис для доступа к значениям в словаре.

import dictionaries

enter = input("enter your selection: ")
selection = dictionaries[enter]  # how to access dictionary
print(selection)

Обновлено

# Import the specific dictionary we want to access
from dictionaries import commands

try:
    enter = input("enter your selection: ")
    # All of the dictionary keys are integers so
    # we need to cast from string to int
    enter_as_int = int(enter)  
    selection = commands[enter_as_int]  # how to access dictionary
    print(selection)
except Exception as e:
    # if the user enters a non-int or an int that is not in 
    # commands then we can expect an Exception
    print(f"There was an error: {str(e)}")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...