将字典添加到列表python-ValueError:字典更新序列元素#0的长度为1;2是必需的
当我尝试将新注释发布到注释列表中时,我不断收到“ValueError:dictionary update sequence元素#0的长度为1;需要2”将字典添加到列表python-ValueError:字典更新序列元素#0的长度为1;2是必需的,python,Python,当我尝试将新注释发布到注释列表中时,我不断收到“ValueError:dictionary update sequence元素#0的长度为1;需要2” # import the Flask class from the flask module from flask import Flask, render_template, request # create the application object app = Flask(__name__) posts=[] @app.route(
# import the Flask class from the flask module
from flask import Flask, render_template, request
# create the application object
app = Flask(__name__)
posts=[]
@app.route('/index')
def index():
user = {'nickname': 'Miguel'}
posts = [
{'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
{'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so
cool!'}
]
return render_template("index.html", title='Home', user=user, posts=posts)
@app.route('/postAnonComment', methods=['POST'])
def SaveDetails():
userName = request.form['user_name']
userMail = request.form['user_mail']
userMessage = request.form['user_message']
newDictionaryItem = newDictionaryItem = "{'author': {'nickname': '{}'},
'body': '{}'}".format(userName, userMessage)
posts.append(dict(newDictionaryItem))
return render_template('index.html', user=userName, posts=posts)
# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)
当您可以直接执行时,创建
dict
的字符串表示并尝试从中提取dict
是低效的
newDictionaryItem = {
'author': {'nickname': userName},
'body': userMessage,
}
posts.append(newDictionaryItem)
您正试图从
str
创建dict
:
newDictionaryItem = """{'author': {'nickname': '%s'}, 'body': '%s'}""" % (userName, userMessage)
posts.append(dict(newDictionaryItem))
^^^^^
Python不会为您执行此解析。要解决此问题,请手动创建字典:
newDictionaryItem = {'author': {'nickname': userName }, 'body': userMessage }
posts.append(newDictionaryItem)
建议不要按您通过字符串使用
dict
的方式执行,但您可以:
posts.append(dict(eval(newDictionaryItem)))
最好只使用正常的dict
赋值:
newDictionaryItem = {'author': {'nickname': userName}, 'body': userMessage}
posts.append(newDictionaryItem)
请发布您的完整错误回溯请修复您的缩进!抱歉,它在我的IDE中正确缩进了。你不能这样做吗?@Dylan:如果你想让我们帮助你找到一个错误,你不能找到,你必须按照你的代码做缩进。这应该不是问题:只需粘贴我们的代码,然后选择代码并将其标记为代码。你可以编辑你的帖子!没有必要在
dict
@matiasccero上调用dict()
:你当然是对的。谢谢你的更正。我已经更正了帖子。