【发布时间】:2011-07-24 06:50:15
【问题描述】:
这是一个非常基本的sn-p adder/viewer/remover。我希望它工作的方式是,用户将输入一个名称(字典键),然后输入文本正文(键的值),以添加条目。例如-“Testsn-p”,它是值“This is a test text sn-p”的键。
我不知道它有什么问题。尝试使用“添加/修改”选项让我输入我想作为键值输入的 sn-p 文本,但它给了我这个错误:TypeError: 'type' object does not support item assignment
此外,尝试使用删除选项只会给我添加/修改选项,而不是删除选项。使用“视图”可以正常工作。
from sys import exit
clip_list = {'test':'whatever, this is a test'}
breaker = "--------------------"
while True:
print "What do you want to do?"
print "[view] [add/modify] [remove] [quit]"
action = raw_input("> ")
if action == "view":
view_choice = raw_input("Enter snippet name to view OR type 'all' for the entire list:\n> ")
if view_choice == 'all':
print clip_list
print breaker
else:
print clip_list[view_choice]
print breaker
elif action == "add" or "modify":
snippet_name = raw_input("Enter snippet name:\n> ")
snippet_input = raw_input("Text:\n> ")
dict[str(snippet_name)] = str(snippet_input)
print "Added!"
elif action == "remove":
snippet_name = raw_input("Enter snippet name to remove:\n> ")
del dict[snippet_name]
print "Deleted!"
elif action == "quit":
print "Goodbye!"
exit(0)
else:
print "What? Please enter a valid command!"
【问题讨论】:
-
你也可以说
elif action in ["add", "modify"]:,而不是elif action == "add" or action == "modify":,如果你有许多条件是“or”在一起,这对可读性很有好处。
标签: python dictionary