繁体   English   中英

在 python 中使用字典时遇到的问题

[英]A problem faced while using dictionaries in python

这是一个名为dictionaries.py的文件,其中包含以下代码:

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

这是另一个名为main.py的文件,它从用户那里获取输入并将其存储在一个名为enter的变量中。 现在此变量包含要从已导入的 dictionaries.py 访问的字典 我已经编写了以下代码,但它给了我一个错误提示 -

selection = dictionaries.enter AttributeError: 模块 'dictionaries' 没有属性 'enter'

import dictionaries

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

您使用不正确的语法来访问字典中的值。

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

如果您的图书馆是:

# ./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"

当您像 'selection = dictionaries.enter' 一样使用它时,python 将搜索 'enter' 作为属性而不是值,尝试像 'selection = dictionaries[enter]' 它应该像这样工作

暂无
暂无

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

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