动态更新字典
Dynamicaly update dictionary
我想根据列表中必须追加的项目动态创建字典。所以我尝试了:
questions = 'my_question'
answers = ['thisisanswer1','thisisanswer2','thisisanswer3']
answers = {"Answer{i}":answers[i] for i in range(0,len(answers))}
dict_replacing = {'Questions': questions}.update(answers)
但是returnsNone
您忘记将 i
放在 for
和 in
之间。
另外,在 "answer{i}"
之前放一个 f
.
正如其他人在评论中所指出的那样,您的代码中存在一些错误。
- 缺少赋值变量
i
- 字典键是一个字符串文字
Answer{i}
,它在每次迭代中都是相同的,并且会覆盖之前的字典键。
- 字典更新和赋值语句
dict_replacing = {'Questions': questions}.update(answers)
#这将return更新操作的结果即None
questions = "my_question"
answers = ["thisisanswer1", "thisisanswer2", "thisisanswer3"]
answers = {<b>f</b>"Answer{i}": answers[i] for <b>i</b> in range(0, len(answers))}
dict_replacing = {"Questions": questions, <b>**answers</b>}
我想根据列表中必须追加的项目动态创建字典。所以我尝试了:
questions = 'my_question'
answers = ['thisisanswer1','thisisanswer2','thisisanswer3']
answers = {"Answer{i}":answers[i] for i in range(0,len(answers))}
dict_replacing = {'Questions': questions}.update(answers)
但是returnsNone
您忘记将 i
放在 for
和 in
之间。
另外,在 "answer{i}"
之前放一个 f
.
正如其他人在评论中所指出的那样,您的代码中存在一些错误。
- 缺少赋值变量
i
- 字典键是一个字符串文字
Answer{i}
,它在每次迭代中都是相同的,并且会覆盖之前的字典键。 - 字典更新和赋值语句
dict_replacing = {'Questions': questions}.update(answers)
#这将return更新操作的结果即None
questions = "my_question"
answers = ["thisisanswer1", "thisisanswer2", "thisisanswer3"]
answers = {<b>f</b>"Answer{i}": answers[i] for <b>i</b> in range(0, len(answers))}
dict_replacing = {"Questions": questions, <b>**answers</b>}