我有以下 json 数据:
hostcreate = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": "my_host",
"port": 10050,
"interfaces": [{
"type": 1,
"main": 1,
"useip": 1,
"ip": "10.100.200.200",
"dns": "",
"port": "10050"
}],
"groups": [{
"groupid": 2
}, {
"groupid": 22
}]
},
"auth": "byese31blahblah",
"id": 1
}
我可以使用如下方式更新现有键的值:
hostcreate['params']['port'] = str(newhostport)
但是,当我尝试向字典添加新的键/值时,出现错误:
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
IndexError: list index out of range
当 count
的值大于 groupid
的可用槽数时,我会收到该错误。换句话说,现在 groupid
有 2 个槽,我可以轻松更新。但是当我尝试为 groupid 添加新的键/值时,我收到上述错误。
我该如何解决这个问题?
更新:
这是代码(不起作用):
numofgroups = len(groupids.split(","))
rnumofgroups = numofgroups - 1
count = 0
existinggids = len(hostcreate['params']['groups']) - 1
while (count <= numofgroups):
eachgroupid = groupids.split(",")[count]
if count <= existinggids:
count = count + 1
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
else:
count = count + 1
hostcreate['params'['groups'].append({
'groupid':int(eachgroupid)
})
每次我运行这个程序时,它都会提示。谁能发现我的代码有什么问题吗?
最佳答案
您必须附加到列表hostcreate['params'['groups'].append({'groupid':in(each groupid)})
关于python - 将新的键/值添加到 json 字典 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55166788/