动态更新字典

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 放在 forin 之间。 另外,在 "answer{i}" 之前放一个 f.

正如其他人在评论中所指出的那样,您的代码中存在一些错误。

  1. 缺少赋值变量i
  2. 字典键是一个字符串文字Answer{i},它在每次迭代中都是相同的,并且会覆盖之前的字典键。
  3. 字典更新和赋值语句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>}