Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将字典添加到列表python-ValueError:字典更新序列元素#0的长度为1;2是必需的_Python - Fatal编程技术网

将字典添加到列表python-ValueError:字典更新序列元素#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(

当我尝试将新注释发布到注释列表中时,我不断收到“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('/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()
:你当然是对的。谢谢你的更正。我已经更正了帖子。