【问题标题】:name variables or append dictionaries命名变量或附加字典
【发布时间】:2020-03-03 20:54:15
【问题描述】:

我正在尝试 根据循环索引创建字典名称,例如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】:

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

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

    您可以通过enumerate获得索引

    【讨论】:

    • 谢谢。它工作得很好。我不敢相信这很容易......
    • @Spad 的 Python 魔法 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2019-06-29
    • 2019-09-19
    • 2011-05-11
    • 2011-09-02
    • 2014-10-01
    相关资源
    最近更新 更多