我有以下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)
})
每次我运行此命令时,都会不断抱怨。谁能发现我的代码有什么问题?
答案 0 :(得分:1)
您必须附加到列表hostcreate['params'['groups'].append({'groupid':int(eachgroupid)})
答案 1 :(得分:0)
hostcreate['params']['groups']
是一个列表,因此您需要append
向其中添加新项目:
hostcreate['params']['groups'].append({
'groupid': int(eachgroupid)
})
更新:
您没有提供MVCE,所以我只能猜测您想做什么。您确实可以重写您在更新部分添加的代码,使其更具Pythonic:
hostceate["params"]["groups"] = [{"groupid": int(g)} for g in groupids.split(",")]
这将替换整个列表,我看到您正在尝试在while循环之前将count初始化为0的情况。
答案 2 :(得分:0)
我会做类似的事情
try:
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
except:
hostcreate['params']['groups'].append({})
hostcreate['params']['groups'][count]['groupid'] = int(eachgroupid)
可能会有更优雅的解决方法,但这只是在groups
列表中添加一个空字典,以便您可以向其中添加key:value