【问题标题】:How to write a value to existing dictionary that has nested dictionary如何将值写入具有嵌套字典的现有字典
【发布时间】:2019-11-27 20:11:35
【问题描述】:

我正在尝试编写一个采用 python 脚本并将其转换为 json 的代码。所以我基本上是在抓取文件并将所需的值添加到我在下面给出的字典中。我需要将多个任务写入字典。

对于 new_data 中的行:

    if re.search(r'task_id=',line ):

        #write to dic['tasks'][0]['task_id'] 

(here there are multiple matches for task_id, so I have to iterate through the list and should be able to write to task_id)

我已经试过了:

dic['tasks'][0]['task_id'] = line.split(":")[1]

但它会抛出list out of index error。我不明白为什么会抛出这个错误。

dic = { 
    "tasks": [{
        "task_id": "1",
        "description": "Short Description.",
        "bitbucket_link": "",
        "can_restart": True,
        "cluster_size": "",
        "notes": ""
    }]
}

虽然预期的输出应该是:

dic = { 
    "tasks": [{
        "task_id": "1",
        "description": "Short Description.",
        "bitbucket_link": "",
        "can_restart": True,
        "cluster_size": "",
        "notes": ""
    }, {
        "task_id": "2",
        "description": "Short Description.",
        "bitbucket_link": "",
        "can_restart": True,
        "cluster_size": "",
        "notes": ""
    }]
}

【问题讨论】:

  • 您能否在developers 键中添加内容?在您给出的示例中,我只看到 tasks 键里面有什么!你明白我在问什么吗?
  • 该错误表示line 中没有:line 是什么?
  • 请添加源字典的sn-p。没有它,我们无法帮助您。另外,您不需要在这里寻求帮助,我们已经知道了。看看我对您的代码所做的编辑,以了解如何更好地格式化代码 sn-ps。
  • for line in new_data: if re.search(r'task_id=',line ): #write to dic['tasks'][0]['task_id'] (这里有多个匹配对于task_id,所以我必须遍历列表并且应该能够写入task_id)

标签: python json dictionary nested


【解决方案1】:

检查类型以确保它是一个字典。索引错误通常是指列表。

print(type(my_dict))

在嵌套字典上对我有用的示例:

anomalies = apList[0]['vap_table'][0]['anomalies_bar_chart']

希望这会有所帮助!

【讨论】:

  • 非常感谢@r1kchartrand。我正在尝试将新数据写入嵌套字典, dic['tasks'][0]['task_id'] = line.split(":")[1] # line 是我文件中我想要的数据写字典
猜你喜欢
  • 2021-12-13
  • 2014-02-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 2018-10-27
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多