如何解决Python 字典:通过输入更新
这里的“anotherName”是模块中的字典,我想根据用户输入更新它。这是怎么做的?说“anotherName[input]”的行不起作用,因为输入是一个内置函数,但我不知道应该怎么做,以另一种方式引用输入。 “ans”引发了同样的错误。
def newPlace():
ans = fieldinR62.get()
for x in anotherName.items():
if ans in anotherName:
print("This place is already stored")
break
if ans not in anotherName:
ans = input
anotherName[input]
top = Toplevel()
top.title("first highly desireable window")
top.geometry("400x200+120+120")
button1 = Button(top,text="Add feature",command=open_window).grid(row=1,column=4,sticky=W,pady=10)
fieldinEMAIL = tk.Entry (top,).grid(row = 2,column = 5,pady=20)
这是我发现可行的另一种解决方案,但现在我需要使其在函数内工作。
d = {"username": "XYZ","email": "xyz@gmail.com","location": "Mumbai"}
r=str(input())
d[r] =' '
print(r)
print(d)
解决方法
函数 input
必须带括号调用。此外,字典由键值对组成,并且一个新的键值对被添加到字典中,如下所示:dict[key] = value
。
您必须替换这 2 行:
ans = input
anotherName[input]
有了这些:
ans = input()
anotherName[key] = ans
其中 key 是每个新输入的唯一值。可能是某种用户 ID,但您必须自己确定。只要键是唯一的,因此不在字典中。您可以使用简单的 if 语句检查字典中是否已存在键:
if key in dict:
# key is already in dict,try new key or throw error.
else:
# key is not already in dict and is safe to use.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。