在嵌套字典中更新相同的值

时间:2018-01-04 03:53:39

标签: json python-2.7 dictionary

我有一个下面显示的字典,我想用新值更新“时间”键(嵌套字典的两个键)。

{
    "mReport": {
        "reports": 1,
        "time": "2017-08-04T16:33:19",
        "m_reports": [{
            "name": "eth0",
            "int": "eth0",
            "type": "data",
            "datatype": "STRING",
            "value": 0,
            "unit": "",
            "time": "2017-08-04T16:33:19"
        }]
    }
}

我尝试了这个,但是我能够更新外部时间键(在mReport下),m_reports下的键根本不可访问。 我的代码,仅适用于外键:

for _, dv1 in kpi_resp.iteritems():
    for key1, dv2 in dv1.iteritems():
        if key1 == 'time':
            dv1["time"] = "2017-08-04T16:33:19"

需要帮助。

1 个答案:

答案 0 :(得分:1)

如果你直接这样做会怎么样:

new_value = "2017-08-04T16:33:19"

kpi_resp["mReport"]["time"] = new_value
kpi_resp["mReport"]["m_reports"][0]["time"] = new_value

或者,如果您需要为所有嵌套词典执行此操作:

new_value = "2017-08-04T16:33:19"

kpi_resp["mReport"]["time"] = new_value
for report in kpi_resp["mReport"]["m_reports"]:
    report["time"] = new_value