名称变量或附加字典

问题描述 投票:0回答:1

我正在尝试根据循环索引创建字典名称,例如mydict_1,mydict_2等。要么将字典追加到一本字典中

通过一个循环,我得到了几组数据,我希望能够一次或一个接一个地访问它们。

for components in fiSentence.findall("components"):
  operation = components.find('operation').text
  target = components.find('target').text
  targetState = components.find('targetState').text
...

所有这些都在字典中:

tempDict = {"operation":operation, "target":target, "targetState":targetState, ...}

然后在循环之外,我尝试将所有它们存储在另一本词典中,但是我只能通过一个列表来做到这一点:

data.append(tempDict)

我想要将它们存储在不同的词典中为:

procedural_Step_1 = {"operation":operation, "target":target, "targetState":targetState}
procedural_Step_2 = {"operation":operation, "target":target, "targetState":targetState}
...

或将它们全部存储在一本字典中:

data = {"procedural_Step_1":{"operation":operation, "target":target, "targetState":targetState}, {"procedural_Step_2":{"operation":operation, "target":target, "targetState":targetState},...}
python dictionary variables append
1个回答
0
投票

您可以在循环之前和循环结束时声明字典data

   data['procedural_step_'+str(index)] = temp_dict

您可以通过enumerate获得的索引

© www.soinside.com 2019 - 2024. All rights reserved.